Invalid PDO query does not return an error

前端 未结 3 856
遇见更好的自我
遇见更好的自我 2021-02-08 00:24

The second SQL statement below returns an error in phpMyAdmin:

SET @num=2000040;
INSERT INTO artikel( artikel_nr, lieferant_nr, bezeichnung_1, bezeichnung_1 )
SE         


        
相关标签:
3条回答
  • 2021-02-08 00:48

    This is expected behavior. Since there are two statements and the first one is valid, you have to use nextRowset()

    try
      {
        $pdo_statement->execute();
        while ($pdo_statement->nextRowset()) {/* https://bugs.php.net/bug.php?id=61613 */};
      }
    

    Source: bugs.php.net/bug.php?id=61613

    0 讨论(0)
  • 2021-02-08 00:52

    If you have the option to use mysqli instead of PDO for the multi query, you can use mysqli_multi_query. As error handling is a little complex, here is my function:

    /**
     * Executes multiple queries at once (separated by semicolons) and discards the results
     *
     * @param string $sql
     * @throws RuntimeException if a query failed
     */
    function multi_query($sql) {
        $mysqli = new mysqli('host', 'user', 'password', 'database');
    
    
        //Execute all queries
        $index = 1;
        if ($mysqli->multi_query($sql)) {
            do {
                // next_result() fails if store_result() is not called
                if ($result = $mysqli->store_result()) {
                    $result->free();
                }
                $has_next = $mysqli->more_results();
                if (!$has_next)
                    return; // all queries successfully executed
                $index++;
            } while ($mysqli->next_result());
        }
        // At this point, either the multi_query() has returned false - which is
        // when the first query failed - or more_results() was true, while next_result()
        // returned false - which is when a different query failed.
    
        $error = $mysqli->error;
        if (!$error)
            $error = $mysqli->errno ? "errno $mysqli->errno" : '(unknown error)';
        throw new RuntimeException("mysqli query $index failed: $error");
    }
    
    0 讨论(0)
  • 2021-02-08 00:53

    By default PDOStatement::execute() doesn't throw any exception, it simply returns false on error. You have to set error handling to PDO::ERRMODE_EXCEPTION through db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION).

    0 讨论(0)
提交回复
热议问题