【问题标题】:Check status of previous MySQL query and execute next query检查上一个 MySQL 查询的状态并执行下一个查询
【发布时间】:2016-01-01 23:56:55
【问题描述】:

我想执行多个 MySQL 查询。下一个查询取决于前一个查询的状态。我需要检查status of the query,在某些情况下还需要检查rowCount()。如果第一个查询返回我想要的内容,则将执行下一个查询,依此类推。如果其中一个失败,整个过程将停止。

我通常nest my queries inside of a try/catch block。有一个更好的方法吗?这是我的代码。我不希望你修复我的代码,只是看看它并给我任何建议。我正在使用PDOMySQL 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) {}

【问题讨论】:

  • 您对这段代码有疑问,还是只是寻求反馈,看看它是否是一个好方法?
  • 我对代码没有任何问题,但我认为这不是一个好习惯。 @肖恩

标签: php mysql sql mysqli pdo


【解决方案1】:

我假设您希望谨慎执行有效的数据库状态。

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    • 2023-03-18
    相关资源
    最近更新 更多