Home » Php » php – Check if database and/or table exists

php – Check if database and/or table exists

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am trying to write a simple installation script using Zend Framework. It’s supposed to run a few tests:

  • test if the database specified in application.ini exists (or if there’s access to it).
  • if it does, test if a table called user exists within the database
  • if it does, check if there’s a site admin user

Should any of the steps fail, the controller will take care of redirecting the user to the proper step of the installation process.

I created a model with the following code:

public function verify () {
    $db = $this->getDefaultAdapter(); //throws exception
    if ($db == null) return self::NO_BATABASE;
    $result = $db->describeTable('user'); //throws exception
    if (empty($result)) return self::NO_USER;
    $result = $db->fetchRow('SELECT * FROM user WHERE id = 1');
    if ($result == null) return self::USER_EMPTY;
    else return self::OK;
}

However, I overestimated the functions I have used. getDefaultAdapter() may return null, but in case there’s no database to connect to, an exception is thrown. Same happens with describeTable(), which throws an exception instead of returning an empty array.

My question is therefore: how do I check whether the database/table exists without getting an exception or error?

How to&Answers:

Rough example :

public function verify () {
    try{
       $db = $this->getDefaultAdapter(); //throws exception
       if ($db == null) return self::NO_BATABASE;
    }catch(Exception $e){
       return self::NO_BATABASE;
    }
    try{
       $result = $db->describeTable('user'); //throws exception
       if (empty($result)) return self::NO_USER;
    }catch(Exception $e){
       return self::NO_USER;
    }
    $result = $db->fetchRow('SELECT * FROM user WHERE id = 1');
    if ($result == null) return self::USER_EMPTY;
    else return self::OK;
}