从表中填充选择列表并将值插入另一个表错误

时间:2016-01-07 09:08:53

标签: php html css for-loop mysqli

我不知怎的被卡住了,可能很傻但是不能安静地工作。 可以说,我有2张桌子 - 位置(盖子,公司,位置) 打印机(pid,盖子,型号,价格) 在我的索引页面中,我有一个表单来添加新的打印机。这里所有都是文本输入字段,但是从下拉框中选择位置。在下拉列表中,将显示公司和位置以便选择,并且当其中一个选择时,位置id将被视为值并且需要被插入到打印机表中以链接到位置表以供以后使用。 一切正常,两列值一起显示可供选择,但即使在选择后,其id值也会被插入到打印机表中。你能告诉我该怎么做吗?

Index.php页面:

<?php
error_reporting(E_ALL ^ E_NOTICE);
?>

<?php include './connect.php'; ?>

<html>

<head>
    <title>Printer Page</title>

</head>

<body>
<?php

if($_POST['addprintbtn']){
$pserial = $_POST['pserial'];
$pmodel = $_POST['pmodel'];
$plocation = $_POST['plocation'];
$pprice = $_POST['pprice'];

$sql2 = mysqli_query($connect, "INSERT INTO printer(pid, model, lid, price) VALUES($pserial, $pmodel, $plocation, $pprice)");

  if($sql2 == false){
    echo "<p style='color:red'>Something is wrong! Please try again!</p> ";
  }
  else
    echo "<p style='color:green'>Printer added successfully!</p>";

}

echo "<form action='./index.php' method='post' class='form'>
<h3>Add a New Printer</h3>
<label>Printer ID/Serial </label>
<input type='text' name='pserial' required /><br/><br/>
<label>Printer Model </label>
<input type='text' name='pmodel' required /><br/><br/>
<label>Printer Price </label>
<input type='number' name='pprice' required /> BDT<br/><br/>
<label>Location </label>
<select name='plocation'>";
$sql= mysqli_query($connect, "select * from location");
foreach ($sql as $row) {
    $loc1=$row['lid'];
    $loc2 = $row['company'];
    $loc3 = $row['location'];
    echo "<option value=\"$loc1\">$loc2, $loc3</option>";
}
echo "<input style='background-color:#557755; color:#ffffff; font-weight:bold; font-size:11px;' name='addprintbtn' type='submit' value='Add Printer'>
</form>";
?>

</body>
</html>

我的数据库连接页面connect.php

<?php

$connect = mysqli_connect("localhost", "root", "", "test");

if(mysqli_connect_errno($connect))
{
        echo 'Failed to connect';
}

?>

但是,当我提交表单时,它不会插入数据并显示错误。 任何帮助将不胜感激!再次感谢!

1 个答案:

答案 0 :(得分:0)

您的insert查询不正确。更改以下声明

$sql2 = mysqli_query($connect, "INSERT INTO printer(pid, model, lid, price) VALUES($pserial, $pmodel, $plocation, $pprice)");

$sql2 = mysqli_query($connect, "INSERT INTO printer (pid, model, lid, price) VALUES ('".$pserial."', '".$pmodel."', '".$plocation."', '".$pprice."')");