Mysql-PDO执行始终返回true,即使我执行了错误的查询:
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!");
}
在表中,列"total_price"的类型为INT。异常也未捕获(PDO::ATTR_ERRMODE为PDO::ERRMODE_Exception)。在"total_price"中插入"0"。我正在尝试使用:
$total_price = "not_int";
$is_int = $sql->bindParam(:total_price, $total_price, PDO::PARAM_INT);
但也返回TRUE($is_int为TRUE)
实际上,"INSERT INTO orders(total_price)VALUES('not_int');"确实有效。
这是因为'not_int'被转换为0,所以如果您检查表,您必须为'total_price'找到一个0的新条目。
对于'$result=$sql->execute();'当然它会返回true;
函数PDOStatement::excute->返回值仅为布尔
错误案例:
$stmt = $pdo->prepare("Your Query");
...
$result = $stmt->execute();
$result->fetch(); // is only boolean
试试看:
$stmt = $pdo->prepare("Your Query");
...
$result = $stmt->execute();
$stmt->fetch(); // return (PDOStatement) or false on failure
触发错误的PDO查询应该抛出异常。触发警告的查询不应该。
无效数据的根行为是MySQL的一个特性,与PHP或PDO无关——您可以在普通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!");
}