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

时间:2013-04-26 00:51:20

标签: php mysql transactions

我目前正在为我的表单使用一个事务,其中包含一个图片上传器但不熟悉事务我不知道如何将以下代码添加到我的事务中。

这是我的交易看起来像

$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");

我试图添加以下3件事

1.定义上传图片所在的文件夹。

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

2.使用下划线替换文件名中的空格的str_replace,并分配给更简单的变量名

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

3.将文件移动到常规图像上传文件夹并重命名

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

使用例外。不要忘记回滚。

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';
    }