PHP: How to check if a MySQL table exists


In this article, we show how to check if a MySQL table exists using PHP.

Using the code below, you can check to see if a MySQL table exists.

<?php 

$user = "user"; 
$password = "password"; 
$host = "host"; 
$dbase = "database"; 
 
$connection= mysqli_connect ($host, $user, $password);
if (!$connection)
{
die ('Could not connect:' . mysqli_error($connection));
}
mysqli_select_db($connection, $dbase);


//Code to see if table exists
$exists = mysqli_query($connection, "select 1 from customers");

if($exists !== false)
{
   echo("This table exists");
}else{
   echo("This table doesn't exist");
}

?>

So once we make the connection to the database, we can then check to see if the table exists.

We create a variable named $exists and set it equal to mysqli_query where we search 1 from the table name.

In this case, we are looking for a table name named customers to see whether it exists.

The $exists variable stores the value of false or a mysqli_result object.

If it is not equal to false, then the table exists. If it is equal to false, the table doesn’t exist.

This is a very quick to way to check.

If you want have the have the table name stored as a variable, the only thing that changes is instead of putting the name of the table name directly into the mysqli_query, you would put the variable name in its place. You then of course have to have the variable initalized somewhere above in the code.

Leave a Reply