Arnold Daniels
Arnold Daniels

Reputation: 16573

How can I get an error when running multiple queries with PDO?

I'm running multiple queries using PDO. If the second query fails, no Exception is thrown.

$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "
DELETE FROM car; 
INSERT INTO car(name, type) SELECT name, from FROM vehicle;
";

try {
    $db->exec($sql);
}
catch (PDOException $e)
{
    echo $e->getMessage();
    die();
}

The above code executes without throwing an exception.

How can I make sure that all queries have run successfully? How can I check which queries have failed?

P.S. I'm using PDO multi query to run MySQL dumps, but any valid .sql file should work.

Upvotes: 10

Views: 3765

Answers (3)

user3594495
user3594495

Reputation: 51

Following code will show how to catch error while running multiple queries. Try avoiding using "DELIMITER //". Queries are generally separately by ";".

<?php
// Create SQL List
$sqlStatements = "SELECT 100;SELECT 200;SELECT 300; Error SELECT 400;SELECT 500;";

// Prepare and execute statements
$options = [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION];
$db = new PDO("mysql:host=127.0.0.1;dbname=test", 'root', '', $options);

// Prepare and execute
$error = false;
$statement = $db->prepare($sqlStatements);
$statement->execute();

// Check error
try{
    do{
        // Print Resultset
        $rowset = $statement->fetchAll(PDO::FETCH_NUM);
        var_dump($rowset);
    }while($statement->nextRowset());

}catch(\Exception $e){
    echo $e->getMessage()."\n";
}
?>

Upvotes: 1

Arnold Daniels
Arnold Daniels

Reputation: 16573

I found the answer in using a prepared statement. After looping through all rowsets, I can check if the last query executed caused an error using $stmt->errorInfo().

$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);

$sql = "
DELETE FROM car; 
INSERT INTO car(name, type) SELECT name, from FROM vehicle;
";

$stmt = $db->prepare($sql);
$stmt->execute();
$i = 0;

do {
  $i++;
} while ($stmt->nextRowset());

$error = $stmt->errorInfo();
if ($error[0] != "00000") {
  echo "Query $i failed: " . $error[2];
  die();
}

Upvotes: 10

SlyChan
SlyChan

Reputation: 769

There's no clear&easy way to do that.

I think, the best way is to read dump file query-by-query and execute one query at a time.

You can also parse error message and extract problem line number if DB driver tells it (like 'unknown identifier 'blabla' on line 666').

Upvotes: -1

Related Questions