Search code examples
phpmysqlzend-framework

Zend MySQL Check if a table exist


I want to know if there is a way to test if a table exists using Zend.
I'm quite new in Zend, I see in a StackOverflow answer this code.

SELECT 1 FROM testtable LIMIT 1;

But if the table doesn't exist it return an error I don't know how to handle SQL errors in the Zend.


Solution

  • If the table might not exist at all, then your current query would fail if executed. One alternative which won't crash even if the table does not exist would be to query the information schema table:

    SELECT
        COUNT(CASE WHEN table_schema = 'yourdb' AND table_name = 'testtable'
                   THEN 1 ELSE 0 END) AS cnt
    FROM information_schema.tables;
    

    The above query would always return a single record containing a count of matching tables. If the above query returns a cnt value of 1, then the table exists, and if it returns 0, then the table does not exist.

    Edit:

    If the database and/or table names would be dynamic, coming from your PHP script, then you may use a prepared statement and bind values for the database/table dynamically. The query does not change much:

    SELECT
        COUNT(CASE WHEN table_schema = ? AND table_name = ? THEN 1 ELSE 0 END) AS cnt
    FROM information_schema.tables;
    

    See the PHP documentation on prepared statements for more information.