Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if database and/or table exists

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?

like image 608
mingos Avatar asked Feb 22 '11 12:02

mingos


Video Answer


1 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;
}
like image 192
Shikiryu Avatar answered Oct 14 '22 07:10

Shikiryu