首页 > 解决方案 > 如何将数据插入两个表?

问题描述

我正在尝试将数据插入数据库中的两个表中。填写完所有字段后,我的脚本正在插入,但我想在不提供时阻止它img_title

像这样张贴表

post_id | title 
3         example title

像这样的图像表

img_id  img_title  post_id
1       nvvm       3

当我没有填写img_title它时,它会像这样插入到图像表中

img_id  img_title post_id
1                 3

我想防止空字段插入数据库

这是我的代码

<?php

if ($_SERVER['REQUEST_METHOD'] == "POST") {
    include "config.php";

    $title = $_POST['title'];
    $img_title = $_POST['img_title'];

    $stmt = $con->prepare("INSERT INTO post(title,post_id) VALUES (?,?)");
    $stmt->bind_param("ss", $title, $post_id);
    $stmt->execute();

    $post_id = mysqli_insert_id($con);

    $stmt = $con->prepare("INSERT INTO images(img_title,post_id,img_id) VALUES (?,?,?)");
    $stmt->bind_param("sss", $img_title, $post_id, $img_id);

    if ($stmt->execute()) {
        echo " successfully";
    } else {
        echo "Failed";
    }
}

标签: phpmysqli

解决方案


尝试exit()在未设置图像标题时强制终止代码执行。

     <?php
        
        if ($_SERVER['REQUEST_METHOD'] == "POST") {
            include "config.php";
            if(!isset($_POST['img_title'])){
                echo 'test';
                exit();       //You prevented further execution of code if title of image is not set
              }
            $title = $_POST['title'];
            $img_title = $_POST['img_title'];
        
            $stmt = $con->prepare("INSERT INTO post(title,post_id) VALUES (?,?)");
            $stmt->bind_param("ss", $title, $post_id);
            $stmt->execute();
        
            $post_id = mysqli_insert_id($con);
        
            $stmt = $con->prepare("INSERT INTO images(img_title,post_id,img_id) VALUES (?,?,?)");
            $stmt->bind_param("sss", $img_title, $post_id, $img_id);
        
            if ($stmt->execute()) {
                echo " successfully";
            } else {
                echo "Failed";
            }
        }

推荐阅读