Php pdo table exist

Check if a database table exists using PHP/PDO

and then catch the error. If you don’t get any error, but resultset with one column containing «1», then the table exists.

Before I go on, I do realise this is a MySQL-specific solution.

While all the solutions mentioned here may work, I (personally) like to keep PDO from throwing exceptions (personal preference, that’s all).

As such, I use the following to test for table creation instead:

SHOW TABLES LIKE 'some_table_of_mine'; 

There’s no error state generated if the table doesn’t exist, you simply get a zero resultset. Works fast and consistently for me.

Here’s a complete function for checking if a table exists.

/** * Check if a table exists in the current database. * * @param PDO $pdo PDO instance connected to a database. * @param string $table Table to search for. * @return bool TRUE if table exists, FALSE if no table found. */ function tableExists($pdo, $table) < // Try a select statement against the table // Run it in try-catch in case PDO is in ERRMODE_EXCEPTION. try < $result = $pdo->query("SELECT 1 FROM LIMIT 1"); > catch (Exception $e) < // We got an exception (table not found) return FALSE; >// Result is either boolean FALSE (no table found) or PDOStatement Object (table found) return $result !== FALSE; > 

Note: PDO will only throw exceptions if it is told to, by default it is silent and throws no exceptions. Thats why we need to check the result as well. See PDO error handling at php.net

Источник

Проверьте, существует ли таблица базы данных с использованием PHP / PDO

Я хочу проверить, существует ли таблица с определенным именем в базе данных, с которой я подключался с использованием PHP и PDO. Он должен работать со всеми базами данных, такими как MySQL, SQLite и т.д.

12 ответов

а затем поймайте ошибку. Если вы не получите никакой ошибки, но resultet с одним столбцом, содержащим «1», тогда таблица существует.

@feihtthief: Есть способы обойти эту проблему. Например, вы можете получить только первый ряд. Или, что еще лучше, даже не выполняйте утверждение, просто подготовьте его.

@MilanBabuškov MilanBabuškov Я не слежу за тем, как подготовка заявления и его невыполнение говорят о том, существует ли таблица. Я что-то пропускаю?

В этом ответе не рассматривается использование PDO или PHP, где в некоторых случаях имеются нюансы, связанные с обработкой исключений.

Здесь полная функция для проверки наличия таблицы.

/** * Check if a table exists in the current database. * * @param PDO $pdo PDO instance connected to a database. * @param string $table Table to search for. * @return bool TRUE if table exists, FALSE if no table found. */ function tableExists($pdo, $table) < // Try a select statement against the table // Run it in try/catch in case PDO is in ERRMODE_EXCEPTION. try < $result = $pdo->query("SELECT 1 FROM $table LIMIT 1"); > catch (Exception $e) < // We got an exception == table not found return FALSE; >// Result is either boolean FALSE (no table found) or PDOStatement Object (table found) return $result !== FALSE; > 

Примечание. PDO будет генерировать исключения только в том случае, если ему сообщают, что по умолчанию он отключен и не генерирует исключений. То почему мы должны проверить результат также. См. обработку ошибок PDO на php.net

Читайте также:  Php вывести php ini

@livefree75 livefree75 Возможно, вы могли бы быть более конкретным? Я не вижу никаких полей, предоставленных клиентом, здесь . возможно, я не уверен в проблеме, которую вы видите в его / ее коде?

@livefree75 livefree75 Почему это должно защищать? если он находится в слое db, защита не должна быть там вставлена. защита и безопасность не подразумевают повсеместное использование функции фильтра \ очистки.

Если вы хотите санировать, сделайте это в начале функции: $table = preg_replace(‘/[^\da-z_]/i’, », $table);

Прежде чем продолжить, я понимаю, что это решение, специфичное для MySQL.

Хотя все решения, упомянутые здесь, могут работать, я (лично) хотел бы, чтобы PDO отбрасывал исключения (личное предпочтение, все).

В качестве такового я использую следующее для проверки для создания таблицы:

SHOW TABLES LIKE 'some_table_of_mine'; 

Не существует состояния ошибки, если таблица не существует, вы просто получаете нулевой набор результатов. Работает быстро и последовательно для меня.

Как часть вашего проекта, создайте представление схемы.

Для Oracle это будет нечто вроде

SELECT TABLE_NAME FROM ALL_TABLES 
SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema = 'mydbname' 

И затем запустите запрос в вашем коде против представления.

@sitilge PDO является ортогональным по отношению к рассматриваемой проблеме. Это просто инструмент для запуска запроса. Это хороший ответ.

@FélixGagnon-Grenier FélixGagnon-Grenier действительно, это инструмент. Однако ОП, скорее всего, хотел бы получить ответ: this is how you do it with PDO ответом this is how you do it with PDO , не так ли?

@DavidTimothyStrauss Я откатил ваши изменения, поскольку они совершенно неуместны. Мало того, что это неверный SQL-код, не было ничего о том, как на самом деле конкатенировать указанную переменную в запросе.

@sitilge может быть, хорошо. Я на самом деле не сильно не согласен, просто « это то, как вы делаете это с помощью PDO », объясняется в каждой тысяче учебников: он называется «Выполнение SQL-запроса». Если кто-то не может понять, что код SQL на самом деле предназначен для запуска, будь то с помощью PDO или чего-то еще, вряд ли можно надеяться, что он будет знать, как использовать подробный ответ .

@FélixGagnon-Grenier FélixGagnon-Grenier О, действительно, вы правы насчет синтаксиса; Я ошибочно предположил, что вы отвечаете на вопрос: (1) как проверить, существует ли конкретная таблица, и (2) сделать это с помощью PDO. Все, что удовлетворяет части # 1, должно включать в себя конкретное имя таблицы, которую ищут. Ваш код этого не делает; это просто перечисляет все таблицы. Создание представления также совершенно не имеет отношения к вопросу. Что касается конкатенации, ваш ответ даже не начинает рассматривать, как сделать это в PHP, что и было задано в вопросе.

Этот ответ также не подходит для третьей части вопроса, а именно переносимости. Ответ не только непереносим; он даже не отвечает, как обращаться с SQLite, чего конкретно хотел этот вопрос.

Читайте также:  Наш первый сайт

«Это то, как вы делаете это с помощью PDO», объясняется в каждой тысяче учебных пособий: оно называется выполнением SQL-запроса ». > На самом деле, правильное выполнение этого с помощью PDO требует получения точных кодов ошибок, относящихся к отсутствующей таблице, из PDOException, что отличается от выполнения обычного запроса, который вы ожидаете выполнить. Если вы перехватываете все исключения (или даже PDOExceptions), вы обнаружите «отсутствующую таблицу», если, скажем, соединение с БД разорвано.

Источник

PHP PDO check if a table with specific name exists in mySQL database

Additionally, you should use parentheses to ensure that the expressions are evaluated in the correct order: Alternatively, use IN: Question: i am using a form (contains only email) that sends data with ajax to my php file where i need to check if the email that the user entered exists in my database table. ex: The strange thing is that if I run a query on the views, this returns the results: general query on sqlite_master find the views: question: why the query does not recognize the views as type=’views’?

PHP PDO check if a table with specific name exists in mySQL database

The following code checks for tables on the database.

function checkdbexists()< global $krdb; return $krdb->query("show tables"); > 

We want to check whether a table called ‘systems’ exists returning 1 if it does and null or 0 if it does not.

array_search('system',$krb->query('show tables')->fetch())!==false; 
select 1 from information_schema.tables where table_name = 'systems' limit 1 
$db_tables = array_keys($pdo->query('show tables')->fetchAll (PDO::FETCH_GROUP)); if(in_array('myTable', $db_tables))

How can i check database table if new data is inserted, You can use trigger like ALTER TRIGGER dbo.Notify ON dbo.Table AFTER INSERT AS. insert message (A new data is inserted into database table) …

How to check if a tables exists using PDO with Idiorm

/** * Check if a table exists in the current database. * * @param PDO $pdo PDO instance connected to a database. * @param string $table Table to search for. * @return bool TRUE if table exists, FALSE if no table found. */ function tableExists($pdo, $table) < // Try a select statement against the table // Run it in try/catch in case PDO is in ERRMODE_EXCEPTION. try < $result = $pdo->query("SELECT 1 FROM $table LIMIT 1"); > catch (Exception $e) < // We got an exception == table not found return FALSE; >// Result is either boolean FALSE (no table found) or PDOStatement Object (table found) return $result !== FALSE; > 
try < $page = ORM::for_table($table)->where('slug', $slug )->find_one(); > (catch $e) < // 404 with an error that table does not exists. >

instead of the «tableExists» function?

If I am understanding your question correctly you want to check if a table exists in a MySQL database.

Q. 1

It should be noted that the two queries are not identical. You’ve got:

$page = ORM::for_table($table)->where('slug', $slug )->find_one(); 

But your second query should be:

$page = ORM::for_table($table)->select_expr(1)->find_one(); 

See the result columns documentation for information.

Q. 2

Yes, Idiorm uses PDO underneath so you’ll get the same pdo exception — this is something you really could just try and see how it works with:

try < $page = ORM::for_table($table)->where('slug', $slug )->find_one(); > (catch $e)

PHP PDO check if a table with specific name exists in, Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. …

Читайте также:  Javascript array two values

PHP SQLITE PDO Check if views OR table exist

I have, apparently, a simple question. As a documentation I can check if TABLE OR VIEWS exist on DataBase. In my app i need to check if both allready existe in db for return custom error. the problem is that I can check if there is a TABLE, but NOT the VIEWS. ex:

 **Working case** $checkTable = $this->db->query("SELECT * FROM sqlite_master WHERE name ='$table' and type='table'", PDO::FETCH_ASSOC); **Not working case** $checkTable = $this->db->query("SELECT * FROM sqlite_master WHERE name ='$table' and type='table' OR type='views'", PDO::FETCH_ASSOC); **Not working case** $checkTable = $this->db->query("SELECT * FROM sqlite_master WHERE name ='$table' and type='views'", PDO::FETCH_ASSOC); 

The strange thing is that if I run a query on the views, this returns the results:

**Working case** $checkTable = $this->db->query("SELECT * FROM VIEWSpeople WHERE name ='$person'", PDO::FETCH_ASSOC); 

general query on sqlite_master find the views:

 **Working case** $checkTable = $this->db->query("SELECT * FROM sqlite_master WHERE name ='$table'", PDO::FETCH_ASSOC); 

question: why the query does not recognize the views as type=’views’? thanks for your time.

The type of a view is not views but view .

Additionally, you should use parentheses to ensure that the expressions are evaluated in the correct order:

. WHERE name ='$table' AND (type='table' OR type='view') 
. WHERE name ='$table' AND type IN ('table', 'view') 

Check if a database exist (MySQL) and if not create it in, Check the return value of mysql_select_db — this function will return true when the database exists and can be selected — i.e., the database might …

In PHP with PDO, how to check if database contains desired value

i am using a form (contains only email) that sends data with ajax to my php file where i need to check if the email that the user entered exists in my database table.

The table contains these columns: id, name, email, timestamp .

In variable $email i have stored the email that the user has added in the form.

i am using PDO to connect to my database with this code

 try < $db = new PDO('mysql:unix_socket=/tmp/mysql51.sock;host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS); >catch (PDOException $e) < echo 'Pripojenie zlyhalo: ' . $e->getMessage(); > $query_user = $db->prepare("SELECT COUNT FROM koniecinvite as pocet WHERE email='$email'"); $query_user->execute(); $pocet = $query_user->fetchObject(); if($pocet>0)< http_response_code(200); echo "Email exists"; >else

It is not working. I know i need to get the count of the rows with the email, but i need some help here.

Can somebody help me with this?

SELECT COUNT FROM koniecinvite as pocet WHERE email='$email'" 
SELECT COUNT(*) FROM koniecinvite as pocet WHERE email='$email'" 

Also $email must be escaped because of the danger of SQL Injection: https://en.wikipedia.org/wiki/SQL_injection

So the code snippet that does the query should be (please keep in note that on string I DO NOT USE THE VARIABLE, but instead a :something that will be raplaced by variable with bindParam):

$query_user = $db->prepare("SELECT COUNT FROM koniecinvite as pocet WHERE email=:email"); $query_user->bindParam(":email","$email") $query_user->execute(); 

Php — How to check if a tables exists using PDO with, If I am understanding your question correctly you want to check if a table exists in a MySQL database. Q. 1. It should be noted that the two queries …

Источник

Оцените статью