Check if MySQL table exists or not [duplicate]

匿名 (未验证) 提交于 2019-12-03 01:42:02

问题:

Possible Duplicate:
MySQL check if a table exists without throwing an exception

I have a dynamic mysql query builder in my project that creates select queries from different tables.
I need to check if the current processing table exists or not.
Imagine that my tables are table1, table2, and table3. My code is something like this:

How can I do this check (Please tell me the simplest way).

回答1:

Updated mysqli version:

if ($result = $mysqli->query("SHOW TABLES LIKE '".$table."'")) {     if($result->num_rows == 1) {         echo "Table exists";     } } else {     echo "Table does not exist"; } 

Original mysql version:

if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1)      echo "Table exists"; else echo "Table does not exist"; 

Referenced from the PHP docs.



回答2:

Taken from another post

$checktable = mysql_query("SHOW TABLES LIKE '$this_table'"); $table_exists = mysql_num_rows($checktable) > 0; 


回答3:

$query = mysqli_query('SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME IN ("table1","table2","table3") AND TABLE_SCHEMA="yourschema"'); $tablesExists = array(); while( null!==($row=mysqli_fetch_row($query)) ){     $tablesExists[] = $row[0]; } 


回答4:

$result = mysql_query("SHOW TABLES FROM $dbname");  while($row = mysql_fetch_row($result))  {     $arr[] = $row[0]; }  if(in_array($table,$arr)) {   echo 'Table exists'; } 


回答5:

You can try this

$query = mysql_query("SELECT * FROM $this_table") or die (mysql_error()); 

or this

$query = mysql_query("SELECT * FROM $this_table") or die ("Table does not exists!"); 

or this

$query = mysql_query("SELECT * FROM $this_table");  if(!$query)    echo "The ".$this_table." does not exists"; 

Hope it helps!



回答6:

Use this query and then check the results.

$query = 'show tables like "test1"'; 


回答7:

MySQL way:

SHOW TABLES LIKE 'pattern';

There's also a deprecated PHP function for listing all db tables, take a look at http://php.net/manual/en/function.mysql-list-tables.php

Checkout that link, there are plenty of useful insight on the comments over there.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!