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 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示