PHP/MySQL - “BEGIN…COMMIT” Not Working

后端 未结 4 1783
萌比男神i
萌比男神i 2021-01-18 04:31

I was searching for a way to insert data into two database tables in a single query in such a way that if one failed, neither saved (I don\'t want orphaned data). I came ac

相关标签:
4条回答
  • Try breaking the lines into multiple php statements:

    $query = "BEGIN";
    mysql_query($query) or die (mysql_error());
    $query = "INSERT INTO content_subpages (title, url_referer) VALUES ('$pagetitle','$url_referer')";
    mysql_query($query) or die (mysql_error());
    
    $query = "INSERT INTO ccm_main_menu (sub_item, sub_item_link,sub_item_sort_order) VALUES ('$pagetitle','$url_referer','$newsort')";
    mysql_query($query) or die (mysql_error())
    
    $query = "COMMIT";
    mysql_query($query) or die (mysql_error());
    
    0 讨论(0)
  • 2021-01-18 04:56

    Try:

     $dbh->beginTransaction();
     $query = "INSERT INTO content_subpages (title, url_referer) VALUES ('$pagetitle','$url_referer');
                INSERT INTO ccm_main_menu (sub_item, sub_item_link,sub_item_sort_order) VALUES ('$pagetitle','$url_referer','$newsort')";
     $dbh->exec($query);
     $dbh->commit();
    

    Btw, Simon Germain got a good point, Transaction will work with tables using InnoDB engine.

    0 讨论(0)
  • 2021-01-18 05:05

    Make sure you're using an InnoDB table and not a MyISAM table, as MyISAM is not transactional.

    To use an InnoDB table, when you create it, after the closing paren, add ENGINE=InnoDB. By default, MyISAM is used.

    0 讨论(0)
  • 2021-01-18 05:07

    you need to use multi_query instead.

    http://php.net/manual/en/mysqli.multi-query.php

    0 讨论(0)
提交回复
热议问题