dqt83336 2013-04-26 00:51
浏览 33
已采纳

如何将此代码实现到事务中?

I'm currently using a Transaction for my form which includes an image uploader but not being familiar with transactions I'm not sure how I can also add the following code to my transaction.

This is what my transaction looks like

$conn->query("START TRANSACTION");
$stmt = $conn->prepare('INSERT INTO articles(article_title, article_text, article_date) VALUES (?, ?, NOW())');
$stmt->bind_param('ss', $_POST['article_name'], $_POST['description']);
$stmt->execute();
$stmt = $conn->prepare('INSERT INTO images (article_id, image_caption, image_filename) VALUES(LAST_INSERT_ID(),?,?)');
$stmt->bind_param('ss', $_POST['image_caption'], $_FILES['image_filename']['name']);
$stmt->execute();
$stmt->close();
$conn->query("COMMIT");

Im trying to add the 3 things below

1.Define the folder to which the uploaded image goes to.

define('UPLOAD_DIR', '../images/');

2.A str_replace to replace spaces in file name with underscores, and assign to simpler variable name

$imageFile = str_replace(' ', '_', $_FILES['upload']['name']);

3.And move the file to the regular image upload folder and rename it

move_uploaded_file($_FILES['upload']['tmp_name'], UPLOAD_DIR.$imageFile);

Thank you for the help!

  • 写回答

1条回答 默认 最新

  • dqgg25493 2013-04-26 01:02
    关注

    Use exceptions. And do not forget about rollback.

    mysqli_report(MYSQLI_REPORT_STRICT); // mysqli will throw exceptions on error
    
    //....
    
    $conn->query("START TRANSACTION");
    try
        {
        define('UPLOAD_DIR', '../images/');
        $imageFile = str_replace(' ', '_', $_FILES['upload']['name']);
        if (!move_uploaded_file($_FILES['upload']['tmp_name'], UPLOAD_DIR . $imageFile))
            throw new Exception('Cannot upload file');
    
        $stmt = $conn->prepare('INSERT INTO articles(article_title, article_text, article_date) VALUES (?, ?, NOW())');
        $stmt->bind_param('ss', $_POST['article_name'], $_POST['description']);
        $stmt->execute();
        $stmt = $conn->prepare('INSERT INTO images (article_id, image_caption, image_filename) VALUES(LAST_INSERT_ID(),?,?)');
        $stmt->bind_param('ss', $_POST['image_caption'], $_FILES['image_filename']['name']);
        $stmt->execute();
        $stmt->close();
        $conn->query("COMMIT");
        echo 'Uploaded';
        } catch (Exception $e)
        {
        $conn->query("ROLLBACK");
        echo 'Error occurred';
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM