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

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!

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