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

前端 未结 3 1813
逝去的感伤
逝去的感伤 2021-01-05 06:24

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

$db = new PDO(\"mysql:host=localhost;dbname=test\", \'root\', \         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-05 07:16

    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();
    }
    

提交回复
热议问题