Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking that a table exists on MySQL [duplicate]

Tags:

php

mysql

I am trying to check whether a table exists, and if so then do some actions. I keep on getting an error telling me that the table does not exist rather than completing my check. Here is the code:

$tableExists = $db->prepare("SHOW TABLES LIKE $table_array");
$tableExists->execute();
if($tableExists->rowCount() > 0) {
   // do some code
 } else {
   echo "Unable to add because table does not exists";
}

UPDATE: Per suggestions below, I now do the following:

$tableExists = $db->prepare("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ?"); 
$tableExists->execute(array($table_array)); 
if(!is_null($tableExist)) { 
    //do something
} else {
    echo "table does not exist;
}

However, the if statement does not seem to work to determine whether the table exists or not. What else could I do?

like image 279
Danconia Avatar asked Aug 05 '13 22:08

Danconia


People also ask

How will you check if a table exists in MySQL?

4.26 The table_exists() Procedure. Tests whether a given table exists as a regular table, a TEMPORARY table, or a view. The procedure returns the table type in an OUT parameter. If both a temporary and a permanent table exist with the given name, TEMPORARY is returned.

Can we duplicate a table in MySQL?

You can duplicate or "clone" a table's contents by executing a CREATE TABLE ... AS SELECT statement: CREATE TABLE new_table AS SELECT * FROM original_table; Please be careful when using this to clone big tables.


2 Answers

Try this:

select case when (select count(*) from INFORMATION_SCHEMA.TABLES where TABLE_NAME='offices') = 1 then 'exists' else 'does not exist' end
like image 51
Brett Poole Avatar answered Sep 18 '22 17:09

Brett Poole


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

ref: check if MySQL table exists or not

like image 40
Salketer Avatar answered Sep 18 '22 17:09

Salketer