0
try {
    $query = $pdo->query("SELECT 1 FROM `classes` LIMIT 1");
} catch (Exception $e) {
    $query = $pdo->prepare("CREATE TABLE `classes`(
    `ID_class` int(11) AUTO_INCREMENT,
    `name` varchar(255),
    PRIMARY KEY(`ID_class`))");

    $query->execute();
}

Hello.

It doesn't catch, if the table doesn't exist.

2 Answers2

0

This is not going to work because, according to the PHP documentation (php.net):

Return Values

PDO::query() returns a PDOStatement object, or FALSE on failure.

So you either need to test if $pdo->query("SELECT 1 FROM 'classes' LIMIT 1") returns false or an alternative like checking if a table exists without using 'select from' (stackoverflow.com).

Community
  • 1
  • 1
Justin Pearce
  • 4,994
  • 2
  • 24
  • 37
0

It worked for me with the PDO ATT_ERRMODE set to ERRMODE_EXCEPTION.

$user = 'test';
$pass = 'test';
$opt  = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];

$db   = new PDO('mysql:host=localhost;dbname=test;charset=utf8' ,
                                    $user ,
                                    $pass ,
                                    $opt
                                    );


try {
    $query = $db->query("SELECT 1 FROM `classes` LIMIT 1");
} catch (Exception $e) {
    $query = $db->prepare("CREATE TABLE `classes`(
    `ID_class` int(11) AUTO_INCREMENT,
    `name` varchar(255),
    PRIMARY KEY(`ID_class`))");

    $query->execute();
}
Dave
  • 5,108
  • 16
  • 30
  • 40