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?
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.
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.
Try this:
select case when (select count(*) from INFORMATION_SCHEMA.TABLES where TABLE_NAME='offices') = 1 then 'exists' else 'does not exist' end
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With