gpt4 book ai didi

PHP - 插入关联表

转载 作者:行者123 更新时间:2023-11-28 23:28:59 26 4
gpt4 key购买 nike

我正在尝试通过表单提交来填充 mysql 关联(多对多)表。基本上,尝试使用此页面将“红旗”关联到一对多“产品”。

Screenshot of input form

表格

<?php

require 'connect-db.php';

$sql = "SELECT ID, prod_name FROM catalog";
$result = mysqli_query($mysqli, $sql);
?>

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8">
<title></title>
</head>

<body>

<p><strong>Add Red Flag:</strong></p>

<form action="addRedFlag.php" method="post" id="rfForm">
<p>Description:
<br/><textarea rows="4" cols="50" name="rfDescription" form="rfForm"></textarea>
<p>Severity: <br/>
<input type="radio" name="severity" value="minor"/>Minor<br/>
<input type="radio" name="severity" value="moderate"/>Moderate<br/>
<input type="radio" name="severity" value="major"/>Major<p/>
<select name="prod_id">
<option value="">Choose a product</option>
<?php while($row = mysqli_fetch_assoc($result)){ ?>
<?php $id = $row['ID']; ?>
<?php $title = $row['prod_name']; ?>
<option value="<?php echo $id; ?>"><?php echo $title; ?></option>
<?php } ?>
</select>
<p/><input type="submit" value="Submit" name="submit" /></form><br>

<a href="captureRedFlag.php"> Reset Form </a><br>
<a href="displayRedFlag.php"> View Red Flag List</a><br>
<a href="../../index.html"> Home</a>

</body>

</html>

PHP 处理程序

<?php

// connect to the database
include("connect-db.php");

$value1 = $_POST['rfDescription'];
$value2 = $_POST['severity'];
$value3 = $_POST['prod_id'];

$sql = "INSERT INTO redFlag (description, severity) VALUES ('$value1', '$value2')";
$sql2 = "SELECT ID FROM redFlag WHERE (description = '$value1')";
$sql3 = "INSERT INTO prod_RF (cat_id, rf_id) VALUES ('$value3', '$value4')";

$result1 = mysqli_query($mysqli, $sql);
$result2 = mysqli_query($mysqli, $sql2);

if ($result1)
{
if ($result2)
{
$row = mysqli_fetch_assoc($result2);
$value4 = $row['ID'];
// echo $value4;
$result3 = mysqli_query($mysqli, $sql3);
if ($result3)
{
echo "success";
}
else {echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);}
}
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}

mysqli_close($mysqli);

?>

执行时,代码成功完成,但 prod_RF 表中 rf_id 的值始终为零。这很奇怪,因为当我取消注释

echo $value4;

行,期望值被打印到屏幕上。出于某种原因,当我尝试使用相同的值($value4)作为 SQL 查询($sql3)的输入时,出现了错误。

感谢您的任何建议,因为我对这一切还很陌生。

最佳答案

更好的方法是使用 MySQL 函数获取最后插入的 ID,这样您就可以跳过第二个查询。

$sql = "INSERT INTO redFlag (description, severity) VALUES ('$value1', '$value2')";
$sql3 = "INSERT INTO prod_RF (cat_id, rf_id) VALUES ('$value3', LAST_INSERT_ID())";

$result1 = mysqli_query($mysqli, $sql);
$result2 = mysqli_query($mysqli, $sql3);
// the $result2 query will insert the rf_id
// so you can test this result to see if it's all successful

这应该会从您的代码中删除大量 PHP。

关于PHP - 插入关联表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38022457/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com