简体   繁体   English

PDO,错误的更新仍然没有例外

[英]PDO, wrong update still no exception

try {
     $query = 'UPDATE keywords SET value = :keyvalue WHERE keyword = :keyname AND document_id = :docId';
     $pdo   = _openConnection();
     $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $pdo->beginTransaction();
     $pdoStatement = $pdo->prepare($query);
     foreach ($keywords as $keyname => $keyval) {
        $pdoStatement->bindParam(':docId', $id, PDO::PARAM_STR);
        $pdoStatement->bindParam(':keyname', $keyname, PDO::PARAM_STR);
        $pdoStatement->bindParam(':keyvalue', $keyval, PDO::PARAM_STR);
        $pdoStatement->execute();
     }
     $res = $pdo->commit();
     var_dump('retornando true', $res);
     return true;
} catch (PDOException $e) {
     $pdo->rollBack();
     echo $e->getMessage();
     return false;
}

The sentence updates a given row identified by KEYWORDNAME and DOCUMENT_ID . 该句子更新KEYWORDNAMEDOCUMENT_ID标识的给定行。 I am sending a wrong keyword name (non-existent) but existent document id. 我发送错误的关键字名称(不存在)但存在文档ID。

Shouldn't it throw an exception for record not found and rollback the operation? 不应该为找不到的记录抛出异常并回滚操作吗? It is always succeeding and returning true (also I see the var_dump) 它总是成功并返回true(我也看到了var_dump)

PS: this is the last portion of the code. PS:这是代码的最后一部分。

No, you are simply updating 0 rows when the WHERE condition is not matched. 不,当WHERE条件不匹配时,您只是更新0行。 Updating, selecting, etc. 0 rows is not an error, these are normal database operations. 更新,选择等等0行不是错误,这些都是正常的数据库操作。

Check the rowCount() to see how many rows are updated and handle that accordingly. 检查rowCount()以查看更新的行数并相应地处理它们。

As far as the database (and thus PDO) is concerned - this is not an error. 就数据库(以及PDO)而言 - 这不是错误。 You performed an update statement, and it successfully updated 0 rows. 您执行了更新语句,并成功更新了0行。

If you want to handle this as an error, you'd have to do it manually: 如果您想将此作为错误处理,则必须手动执行:

$res = $pdo->commit();
if ($pdo->rowCount() == 0) {
    # some exception treatment
}

A query which doesn't match any records is NOT an error. 与任何记录都不匹配的查询不是错误。 It's just an empty result set, which is a perfectly valid result. 它只是一个空结果集,这是一个完全有效的结果。

The only time you'd get an exception from the query is if there was an actual problem with the query itself, the connection to the db, etc... eg A syntax error in the DB, connection failure, permission denied on whatever table(s) you're accessing, etc... 您从查询中获得异常的唯一时间是查询本身存在实际问题,与数据库的连接等等...例如,DB中的语法错误,连接失败,任何表上的权限被拒绝(s)您正在访问等...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM