PHP & mySQL: Simple code to implement Transaction - Commit & Rollback

前端 未结 2 1216
攒了一身酷
攒了一身酷 2020-12-16 05:06

MY PLATFORM:

PHP & mySQL

MY SITUATION:

I am trying to implement transactions within my code. I tried to follow

相关标签:
2条回答
  • 2020-12-16 05:14

    You don't need to use mysqli. You can just issue the transaction commands as queries.

    So for your example:

    mysql_query("start transaction;");
    
    //db_res calls a custom function that performs a mysql_query on the query
    $res1 = db_res("SELECT c1, c2 FROM t1 WHERE c5 = 3");
    $res2 = db_res("UPDATE t2 SET c1 = 5 WHERE c2 = 10");
    $res3 = db_res("DELETE FROM t3 WHERE c1 = 20");
    
    if( $res1 && $res2 && $res3 )
    {
      mysql_query("commit;");
    }
    else
    {
      mysql_query("rollback;");
    }
    

    By they way if you are thinking about upgrading to mysqli, please don't. Upgrade to PDO instead, it's much more sane.

    0 讨论(0)
  • 2020-12-16 05:21

    You need to use the mysqli extension to use this functionality.

    See: autocommit(), commit(), and rollback()

    <?php
    $link = mysqli_connect("localhost", "my_user", "my_password", "world");
    
    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    
    /* disable autocommit */
    mysqli_autocommit($link, FALSE);
    
    mysqli_query($link, "CREATE TABLE myCity LIKE City");
    mysqli_query($link, "ALTER TABLE myCity Type=InnoDB");
    mysqli_query($link, "INSERT INTO myCity SELECT * FROM City LIMIT 50");
    
    /* commit insert */
    mysqli_commit($link);
    
    /* delete all rows */
    mysqli_query($link, "DELETE FROM myCity");
    
    if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) {
        $row = mysqli_fetch_row($result);
        printf("%d rows in table myCity.\n", $row[0]);
        /* Free result */
        mysqli_free_result($result);
    }
    
    /* Rollback */
    mysqli_rollback($link);
    
    if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) {
        $row = mysqli_fetch_row($result);
        printf("%d rows in table myCity (after rollback).\n", $row[0]);
        /* Free result */
        mysqli_free_result($result);
    }
    
    /* Drop table myCity */
    mysqli_query($link, "DROP TABLE myCity");
    
    mysqli_close($link);
    ?>
    
    0 讨论(0)
提交回复
热议问题