我想执行多个MySQL查询。下一个查询取决于上一个查询的状态。我需要检查status of the query
,在某些情况下还要检查rowCount()
。如果第一个查询返回我想要的内容,那么将执行下一个查询,依此类推。如果其中一个查询失败,整个过程将停止。
我通常nest my queries inside of a try/catch block
。有更好的方法吗?这是我的密码。我不想让你修改我的代码,只要看看它,给我任何建议。我使用PDO
和MySQL 5.6.26
。
感谢
$updated = false;
//#1
$query = "select username, forgot_code, time, valid from forgot_requests where forgot_code = :forgot_code";
try {
$run_query = $db->prepare($query);
$run_query->execute(array(':forgot_code' => $_POST['forgot_code']));
$data = $run_query->fetch(PDO::FETCH_OBJ);
//13min = 780s
if($run_query->rowCount() == 1 && (time() - $data->time < 7800000) && $data->valid) {
//#2
$query = "update users set password = :password where username = :username";
try {
$run_query = $db->prepare($query);
$run_query->execute(array(
':password' => password_hash($_POST['password'], PASSWORD_DEFAULT),
':username' => $data->username
));
//#3
$query = "update forgot_requests set valid = 0 where forgot_code = :forgot_code";
try {
$run_query = $db->prepare($query);
$run_query->execute(array(':forgot_code' => $_POST['forgot_code']));
//update
$updated = true;
} catch(PDOException $e) {}
} catch(PDOException $e) {}
}
} catch(PDOException $e) {}
我假设您希望使用预先注意事项强制执行有效的数据库状态。
MySQL和PDO为您提供了事务的概念,以确保一系列sql语句只能一起执行。
示例
<?php
$db->beginTransaction();
// Query 2
$query = "update users set password = :password where username = :username";
$run_query = $db->prepare($query);
$run_query->execute(array(
':password' => password_hash($_POST['password'], PASSWORD_DEFAULT),
':username' => $data->username
));
// Query 3
$query = "update forgot_requests set valid = 0 where forgot_code = :forgot_code";
$run_query = $db->prepare($query);
$run_query->execute(array(':forgot_code' => $_POST['forgot_code']));
// All queries will be executed or no query will be executed
$db->commit();
?>
如果你遇到任何问题,你可以回滚交易:
<?php
$db->rollBack();
?>
有关详细信息,请参阅MySql手册:(http://dev.mysql.com/doc/refman/5.7/en/commit.html)和php文档中(http://php.net/manual/de/pdo.begintransaction.php)