Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if MySQL table exists or not [duplicate]

Tags:

php

mysql

exists

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:

<?php for($i = 1 ; $i <= 3 ; $i++) {    $this_table = 'table'.$i;    $query = mysql_query("SELECT * FROM $this_table");    // ... } ?> 

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

like image 339
Mohammad Saberi Avatar asked Jan 25 '12 18:01

Mohammad Saberi


People also ask

What is Information_schema tables in MySQL?

INFORMATION_SCHEMA provides access to database metadata, information about the MySQL server such as the name of a database or table, the data type of a column, or access privileges. Other terms that are sometimes used for this information are data dictionary and system catalog.


2 Answers

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.

like image 190
afuzzyllama Avatar answered Sep 24 '22 07:09

afuzzyllama


Taken from another post

$checktable = mysql_query("SHOW TABLES LIKE '$this_table'"); $table_exists = mysql_num_rows($checktable) > 0; 
like image 27
bowlerae Avatar answered Sep 26 '22 07:09

bowlerae