duanhe6464 2014-08-29 12:05
浏览 37

mysqli_transaction不起作用或我误解了

MY php code for mysqli transaction is

<?php

/*db connection*/

$conn = mysqli_connect("localhost", "root", "", "test");

mysqli_autocommit($conn, FALSE);

$insert1 = mysqli_query($conn, "INSERT INTO user(name,age,gender) VALUES('DEEPU', 24, 'male')");

$insert2 = mysqli_query($conn, "INSERT INTO user(name,age,gender2) VALUES('ANIL', 25, 'male')");

mysqli_commit($conn);

mysqli_close($conn);

?>

I know mysqli transaction is used for, If any operation within the transaction fails, the entire transaction will fail.

Problem:

In my code second query is wrong, it uses gender2 instead of gender. Since one query is failed, the entire transaction should fail. But here the first query execute and data is inserted in table. I expect no data will insert in table because the second query is fail.

Is any mistake in my code?? OR I totally misunderstand the point.

If I use

 mysqli_rollback($conn);

it brings to the pre-transactional state.

NOTE:I am using innoDB engine.

What I need

If both query is correct: data should insert.

If one is correct and other is wrong: no data will insert.

Pease help...Thank you.

  • 写回答

1条回答 默认 最新

  • douguanci9158 2014-08-29 12:29
    关注

    mysqli_query returns true on succesful query. You can use this to commit if both queries succeed and else rollback if either fails.

    $conn = mysqli_connect("localhost", "root", "", "test");
    
    mysqli_autocommit($conn, FALSE);
    
    $query1 = "INSERT INTO user(name,age,gender) VALUES('DEEPU', 24, 'male')";    
    $query2 = "INSERT INTO user(name,age,gender2) VALUES('ANIL', 25, 'male')";
    
    if(mysqli_query($conn, $query1) && mysqli_query($conn, $query2))
    {
         mysqli_commit($conn);
    }else
    {
         mysqli_rollback($conn);
    }
    
    mysqli_close($conn);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答