Mysql PDO执行总是返回TRUE

时间:2015-02-17 20:45:43

标签: php mysql pdo

即使我做错了查询,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为真)

4 个答案:

答案 0 :(得分:1)

实际上,“INSERT INTO orders(total_price)VALUES('not_int');”确实有效。

那是因为'not_int'被转换为0 ,所以如果你检查你的表,你必须找到一个0为'total_price'的新条目。

for '$ result = $ sql-> execute();'原因是它会返回true;

答案 1 :(得分:1)

触发错误的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

答案 2 :(得分:0)

试试这个:

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!");
}

答案 3 :(得分:0)

功能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