Insert into 2 tables from 1 form. Mysql Transaction?

后端 未结 3 1811
南方客
南方客 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 17:49
    $sql ='START TRANSACTION;
           INSERT INTO articles (article_id,article_title, article_text, article_date) VALUES (NULL,?, ?, NOW());
           INSERT INTO images (article_id, image_caption) VALUES(LAST_INSERT_ID(),?);
           COMMIT;';
    
    0 讨论(0)
  • 2021-01-19 17:51
    $mysqli->query("START TRANSACTION");
    $stmt = $mysqli->prepare('INSERT INTO articles(article_title, article_text, article_date) VALUES (?, ?, NOW())');
    $stmt->bind_param('ss', $_POST['article_name'], $_POST['description']);
    $stmt->execute();
    $stmt = $mysqli->prepare('INSERT INTO images (article_id, image_caption) VALUES(LAST_INSERT_ID(),?)');
    $stmt->bind_param('s', $_POST['image_caption']);
    $stmt->execute();
    $stmt->close();
    $mysqli->query("COMMIT");
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
提交回复
热议问题