php - 如何将数据插入两个表?
问题描述
我正在尝试将数据插入数据库中的两个表中。填写完所有字段后,我的脚本正在插入,但我想在不提供时阻止它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";
}
}
解决方案
尝试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";
}
}
推荐阅读
- graphql - 数据不会通过 graphql 突变更新到 Dynamodb,只有 _version 更新
- r - 如何根据 M 或 F 以两种不同颜色创建年龄与骨密度的散点图
- testng - TestNG setUpMethod() 问题
- html - 为什么@media 查询不起作用?我已经尝试了我想的一切。如果这很重要,我正在开发 Angular 10
- r - R boxplot 基于另一列中的值的子集列
- ubuntu - 如何安装 Verascript?错误“zsh:未找到匹配项:../veracrypt-*.tar.bz2”
- hive - 如何通过选择插入?
- azure - 如何将 Web App 连接到 Storage Account Container 并利用它来提供文件?
- unit-testing - 模拟 android.graphics.Rect
- ruby-on-rails - 有没有办法为入站 ema 手动指定 MIME 标头