Friday, 16 November 2018

MySQL check if a table exists without throwing an exception

What is the best way to check if a table exists in MySQL (preferably via PDO in PHP) 
without throwing an exception. I do not feel like parsing the results of "SHOW TABLES 
LIKE" et cetera. There must be some sort of boolean query?

 Answers


I don't know the PDO syntax for it, but this seems pretty straight-forward:
$result = mysql_query("SHOW TABLES LIKE 'myTable'");
$tableExists = mysql_num_rows($result) > 0;



Using mysqli i've created following function. Asuming you have an mysqli instance called 
$con.
function table_exist($table){
    global $con;
    $table = $con->real_escape_string($table);
    $sql = "show tables like '".$table."'";
    $res = $con->query($sql);
    return ($res->num_rows > 0);
}
Hope it helps.
Warning: as sugested by @jcaron this function could be vulnerable to sqlinjection attacs, 
so make sure your $table var is clean or even better use parameterised queries.



This is posted simply if anyone comes looking for this question. Even though its been 
answered a bit. Some of the replies make it more complex than it needed to be.
For mysql* I used :
if (mysqli_num_rows(
    mysqli_query(
                    $con,"SHOW TABLES LIKE '" . $table . "'")
                ) > 0
        or die ("No table set")
    ){
In PDO I used:
if ($con->query(
                   "SHOW TABLES LIKE '" . $table . "'"
               )->rowCount() > 0
        or die("No table set")
   ){
With this I just push the else condition into or. And for my needs I only simply need die.
 Though you can set or to other things. Some might prefer the if/ else if/else. Which is 
then to remove or and then supply if/else if/else.



$q = "SHOW TABLES";
$res = mysql_query($q, $con);
if ($res)
while ( $row = mysql_fetch_array($res, MYSQL_ASSOC) )
{
    foreach( $row as $key => $value )
    {
        if ( $value = BTABLE )  // BTABLE IS A DEFINED NAME OF TABLE
            echo "exist";
        else
            echo "not exist";
    }
}



If the reason for wanting to do this is is conditional table creation, then 
'CREATE TABLE IF NOT EXISTS' seems ideal for the job. 
Until I discovered this, I used the 'DESCRIBE' method above. 

0 comments:

Post a Comment