Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQLi how to check if table exists? [duplicate]

Tags:

php

mysqli

I want to create table by app if there's no such table. But doing it for the first time... Need some help, tho

 //connecting...
$mysqli = new mysqli($db_params['host'], $db_params['login'],   $db_params['pass'], $db_params['name']);

if ($mysqli->query("SHOW TABLES LIKE `products`")){
echo ' YES';
} else echo 'no'; 

It always says NO.

like image 796
Andrew Nevskiy Avatar asked Oct 28 '25 12:10

Andrew Nevskiy


2 Answers

Read their documentation? https://dev.mysql.com/doc/refman/5.5/en/replication-features-create-if-not-exists.html Seems like you can do that easily:

CREATE TABLE IF NOT EXISTS `products`

This way you don't have to check first whether a table exists or not, you just create one if it doesn't.

And it seems like you have a syntax error, which is probably the reason why your code keeps returning "no". This should work:

SHOW TABLES LIKE 'products';

Just use single or double quotes, no backticks like `.

You use backticks (`) for table and column names, single (') or double quotes (") for strings, in this case you are giving a string so you should use single or double quotes.

like image 181
Erik van de Ven Avatar answered Oct 30 '25 03:10

Erik van de Ven


Use PHP DESCRIBE statement.

if(mysql_query("DESCRIBE `table_name`")) {
    // Exists
}
like image 44
Hiren Makwana Avatar answered Oct 30 '25 03:10

Hiren Makwana