PHP - 插入关联表

时间:2016-06-24 21:37:25

标签: php mysql

我试图通过表单提交填充mysql关联(多对多)表。基本上,尝试使用此页面关联"红旗"一对多"产品"。

Screenshot of input form

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 HANDLER

<?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)的输入时,某些内容会失败。

感谢您提出任何建议,因为我对这一切都很陌生。

2 个答案:

答案 0 :(得分:1)

更好的方法是使用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。

答案 1 :(得分:0)

看起来$value4$sql3字符串制作完成之后才定义。在定义$sql3后尝试定义$value4