Smash
Smash

Reputation: 513

How to check is the table exists or not in MySQLi?

thats what I'm doing:

$mysqli = new mysqli($db_host,$db_user,$db_pass,$db_name);
$result = $mysqli->query("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ".$db_name." AND table_name = users");
$nr = $result->num_rows; // 77 line
var_dump($nr);
$mysqli->close();

But the errors says:

Notice: Trying to get property of non-object in test.php on line 77
NULL

Upvotes: 0

Views: 631

Answers (3)

Gordon Linoff
Gordon Linoff

Reputation: 1269633

For your method to work, you need quotes around the string constants:

SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = '".$db_name."' AND table_name = 'users';

However, for your method to really work, do this:

SELECT 1
FROM information_schema.tables
WHERE table_schema = '".$db_name."' AND table_name = 'users';

You are looking at the number of rows being returned, not the value of count(*).

Upvotes: 1

CodeAngry
CodeAngry

Reputation: 12985

SELECT COUNT(*) FROM `table_name` WHERE FALSE;

:-)

Success means table exists, failure... means it doesn't!

Upvotes: -1

Ferrakkem Bhuiyan
Ferrakkem Bhuiyan

Reputation: 2783

you can also check by using this statement SHOW TABLES LIKE 'tablename';

Upvotes: 2

Related Questions