Search code examples
phpmysqlpdodatabase

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?


Solution

  • Querying the information_schema database using prepared statement looks like the most reliable and secure solution.

    $sql = "SELECT 1 FROM information_schema.tables 
            WHERE table_schema = database() AND table_name = ?";
    $stmt =  $pdo->prepare($sql);
    $stmt->execute([$tableName]);
    $exists = (bool)$stmt->fetchColumn();