Insert into 2 tables from 1 form. Mysql Transaction?

后端 未结 3 1810
南方客
南方客 2021-01-19 17:07

The user will create an article and submit an image with it.

+The article will go to the articles table.

+The image will go to images table (so that it can

3条回答
  •  抹茶落季
    2021-01-19 18:10

    It looks like you are using PDO (nice!). With PDO, you can get your transactions in an easy way with beginTransaction() and commit()

    Your code would look like:

    $pdo->beginTransaction();
    // .. fire your 'normal' queries.
    // .. and yet some more queries
    $pdo->commit();
    

    Then, I'd personally write separate INSERT queries in just two separate statements. More readable in my opinion.

    Example:

    $pdo->beginTransaction();
    
    $first = $pdo->prepare('INSERT INTO table (field, otherField) VALUES(?,?)');
    $second = $pdo->prepare('INSERT INTO table (field, otherField) VALUES(?,?)');
    
    $first->execute(array( .. your data (values) .. ));
    $second->execute(array( .. your data (values) .. ));
    
    $pdo->commit();
    

提交回复
热议问题