Mysql PDO执行始终返回TRUE
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命令(total_price)VALUES('not_int');” 确实有效。
那是因为'not_int'被转换为0 ,所以如果你检查你的表,你必须找到一个'total_price'为0的新条目。
for'$ result = $ sql-> execute();' 因为它会返回true;
触发错误的PDO查询应引发异常。 触发警告的查询不应该。
无效数据的根本行为是与PHP或PDO无关的MySQL特性 - 您可以在纯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/69571.html