1

我目前正在为我的表单使用事务,其中包括图像上传器,但不熟悉事务我不确定如何将以下代码添加到我的事务中。

这就是我的交易的样子

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

我试图在下面添加三件事

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

感谢您的帮助!

4

1 回答 1

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';
    }
于 2013-04-26T01:02:07.050 回答