我有2个嵌套表。父表行包含子表。如果需要,两个表都可以通过添加按钮添加行。父表值插入数据库中的product_size表,子表值插入product_color表中。父表包含大小,子表包含该大小的项目的颜色和数量。我想在父表行中插入子表值(颜色和数量)。表示父第一行子表值应仅插入父第一行,而父表第二行中的子表值应插入父第二行。目前,我的代码获取父表的所有行中的所有子表值,并在第一行中插入数据库中,然后再次从父表的所有行中获取所有子表值,并在数据库的第二行中插入父表。请检查我的代码,并帮助我指出代码中的问题所在。 / PHP代码 /
if (isset($_POST['submit']))
{
$con=mysqli_connect("localhost", "root", "");
mysqli_select_db($con,"login");
for ($i=0; $i<count($_POST['size']); $i++){
$size = $_POST['size'][$i];
$qry1="INSERT INTO product_size (product_size) VALUES ('$size')";
$result1=mysqli_query($con,$qry1);
$product_size_id = mysqli_insert_id($con);
for ($j=0; $j<count($_POST['color']); $j++){
$quantity = $_POST['dress_quantity'][$j];
$color = $_POST['color'][$j];
$qry2="INSERT INTO product_color (product_size_id, product_color, product_quantity) VALUES ('$product_size_id', '$color', '$quantity')";
$result2=mysqli_query($con,$qry2);
if($result2)
{
echo '<script>alert("Record Added Successfully!")</script>';
echo '<script>window.location="try.php"</script>';
}
else
{
die("Error While Adding Stock! Please Try Again.");
}
}
}
}
答案 0 :(得分:0)
我在本地服务器上测试过。工作很好
$con=mysqli_connect("localhost", "root", "");
mysqli_select_db($con,"login");
// $size1 = array("50", "60", "70");
// $color1 =array("red", "blue", "green");
// $quantity1 = array("10", "20", "30");
for ($i=0; $i<count($_POST['size']); $i++){
$size = $size1[$i];
$qry1="INSERT INTO product_size (product_size) VALUES ('$size')";
$result1=mysqli_query($con,$qry1);
var_dump($result1);
echo "<br>";
$product_size_id = mysqli_insert_id($con);
for ($j=0; $j<count($size); $j++){
$quantity = $_POST['dress_quantity'][$i];
$color = $_POST['color'][$i];
$qry2="INSERT INTO product_color (product_size_id, product_color, product_quantity) VALUES ('$product_size_id', '$color', '$quantity')";
$result2=mysqli_query($con,$qry2);
if($result2)
{
echo '<script>alert("Record Added Successfully!")</script>';
// echo '<script>window.location="try.php"</script>';
}
else
{
die("Error While Adding Stock! Please Try Again.");
}
}
}