php - 如何使用 commit() 查找记录插入到 mysql

标签 php mysql

抱歉这个初学者问题,我不是 PHP 开发人员,但现在我正在努力学习它。

我想在 MySQL 数据库中添加记录并且我正在使用事务锁。

我的代码如下。

$SqlQuery="INSERT INTO tab_photo VALUES('$PhotoID','$ProjectId','$Day','$barCode','$photoName','$PhotoXml')";

$waiting = true;
while($waiting) {
    try {
        // save border data
        $stmt = $conn->prepare($SqlQuery);
        $conn->beginTransaction();
        $stmt->execute();
        sleep(1);

        $x=$conn->commit();
        echo "x value-".$x;

        echo "Success";
        $waiting = false;
    }
    catch (PDOException $e){
        echo "Failled :".$PhotoID."-".$PhotoID;
        if(stripos($e->getMessage(), 'DATABASE IS LOCKED') !== false) {
            // This should be specific to SQLite, sleep for 0.25 seconds
            // and try again.  We do have to commit the open transaction first though
            $conn->commit();
            usleep(250000);
        } else {
            $conn->rollBack();
            throw $e;
        }
    }
}

在这里作为它给出的输出,

x value-1 Success

但实际上这条记录并没有添加到数据库中。

我的问题:

  1. 连commit都成功了(输出1)怎么没有加入到数据库中?
  2. 如何检查记录是否已添加到数据库中? ( 有没有办法不用写 select 语句就可以找到它?

最佳答案

据我了解,您希望在语句执行失败时抛出 PDOException。但正如我所见,在这种情况下默认情况下不会抛出异常。 查看如何更改 here

假设在你的情况下你应该有这样的代码:

$conn = new PDO($connection_string); 
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // this will force PDO to throw exception when SQL statement fails instead of simply setting an error.

假设这适合您。

请注意,您不应该使用

$SqlQuery="INSERT INTO tab_photo VALUES('$PhotoID','$ProjectId','$Day','$barCode','$photoName','$PhotoXml')";

取而代之的是,你应该使用参数绑定(bind):

$SqlQuery="INSERT INTO tab_photo VALUES(:PhotoID,:ProjectId,:Day,:barCode,:photoName,:PhotoXml)";
$stmt = $conn->prepare($SqlQuery);
$conn->beginTransaction();
$stmt->execute(array(':PhotoID' => $PhotoID, ':ProjectId' => $ProjectId, ....));
sleep(1);

参见 this了解更多详情。

关于php - 如何使用 commit() 查找记录插入到 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14355830/

相关文章:

使用 HTML 变量进行 PHP 分页

python - psycopg2 lobject 类 - 使用位流插入大对象

mysql - SQL:基于另一个字段值的条件字段输出

使用代理的 PHP Curl http 请求有 95% 的时间失败,为什么?

javascript - 使用 PHP 的 Chrome native 消息传递

mysql - 无法创建存储过程 : Syntax error

mysql - 如何轻松安全地远程连接到postgres或mysql?

mysql - ORDER BY 是否会影响连接 View 中的性能?

javascript - 检查某些Web资源是否存在于服务器端或客户端更好?

php - 获取 Woocommerce 订阅开始日期