这是我的类别表。基本上有一个类别和子类别。 ParentCategoryId 是类别下的子类别。例如,我有三个 ParentCategoryID 1,这意味着它是 category_id 1 下的子类别,因此 isSubCategory 设置为 1,表示是的,它是一个子类别,0 意味着它是一个类别,这就是为什么前四个数据的 parentCategryID 为空的原因,因为它们是类别
我已经有一个“添加类别”功能,现在我想要一个“添加子类别”功能,但我很困惑我将如何执行我通常的 php 查询。
<form method="POST">
<?php
if(isset($_POST['submit'])){
include 'testdb.php';
$addcategory = $_POST['categoryname'];
$parentcategory = $_POST['parentcategoryID'];
$query = mysqli_query($con, "SELECT categoryname FROM category WHERE categoryname = '.$addcategory.'");
$insert = mysqli_query($con, "INSERT INTO category (`categoryname`,`ParentCategoryID`,`isSubCategory`) VALUES ('$addcategory','$parentcategory','1')");
if(!$insert){
echo mysqli_error($con);
}
else{
echo 'Category successfully added!';
}
}
?>
最佳答案
外键在同一个表中不是自引用的。如果您的子类别在不同的表中(我建议 - 上面的解决方案真的很困惑),那么外键将使您的插入功能更容易。
无论如何,如果您只是想添加一个新的子类别;
$addcategory = $_POST['categoryname'];
$parentcategory = $_POST['parentcategory'];
$insert = mysqli_query($con,
"INSERT INTO category
(`categoryname`,
`ParentCategoryID`,
`isSubCategory`)
VALUES
('$addcategory',
'$parentcategory'
'1')");
另外,考虑使用准备好的语句.. 或者至少在你正在接受的 POST 参数上运行 mysqli_escape_string.. 让它们保持原样将允许我插入一个类别,如 '; DROP TABLE 用户;.
关于javascript - 在外键表 PHP 中插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41774847/