Mysql PDO execute always return TRUE

Mysql PDO execute always return true, even if i do a wrong query:

try {
    $sql = $this->db->prepare("INSERT INTO orders (total_price) VALUES ('not_int');");
    $result = $sql->execute();  // WHY TRUE??
} catch (Exception $e) {
    die("Oh noes! There's an error in the query!");
}

In table, type of column 'total_price' is INT. Exception also not catch (PDO::ATTR_ERRMODE is PDO::ERRMODE_EXCEPTION). In 'total_price' inserts '0'. I'm try to use:

$total_price = "not_int";
$is_int = $sql->bindParam(:total_price, $total_price, PDO::PARAM_INT);

but also returns TRUE ($is_int is true)


actually, "INSERT INTO orders (total_price) VALUES ('not_int');" does work.

that's because 'not_int' was converted to 0 ,So If you check your table , You must find a new entry with 0 for 'total_price'.

for '$result = $sql->execute();' Of cause it would return true;


A PDO query that triggers errors should throw an exception. A query that triggers warnings should not.

The root behaviour with invalid data is a MySQL peculiarity that has nothing to do with PHP or PDO—you can reproduce it in plain SQL:

mysql> CREATE TABLE orders (
    ->  orders_id INT(10) UNSIGNED AUTO_INCREMENT,
    ->  total_price INT,
    ->  PRIMARY KEY (orders_id)
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> SET @@SESSION.sql_mode='';
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO orders (total_price) VALUES ('not_int');
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> SHOW WARNINGS;
+---------+------+----------------------------------------------------------------------+
| Level   | Code | Message                                                              |
+---------+------+----------------------------------------------------------------------+
| Warning | 1366 | Incorrect integer value: 'not_int' for column 'total_price' at row 1 |
+---------+------+----------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM orders;
+-----------+-------------+
| orders_id | total_price |
+-----------+-------------+
|         1 |           0 |
+-----------+-------------+
1 row in set (0.00 sec)

mysql> SET @@SESSION.sql_mode='TRADITIONAL';
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO orders (total_price) VALUES ('not_int');
ERROR 1366 (HY000): Incorrect integer value: 'not_int' for column 'total_price' at row 1

尝试这个:

try {
    $sql = $this->db->prepare("INSERT INTO orders (total_price) VALUES ('not_int');");
    $result = $sql->execute();  // WHY TRUE??
catch( PDOException $e ) {
    die("Oh noes! There's an error in the query!");
}
链接地址: http://www.djcxy.com/p/69572.html

上一篇: 在名称空间中调用PDO :: setAttribute

下一篇: Mysql PDO执行始终返回TRUE