从下拉列表提交

时间:2017-11-19 07:53:58

标签: php html mysql database

我正在尝试从我的下拉列表中单击选项后插入表单中的值。但是,它一直告诉我, submit.php LINE 4 第5行有错误。我不知道我的$ _POST语句有什么问题。

请赐教,我是PHP和HTML的新手。

以下是我的下拉列表的代码。

<!DOCTYPE HTML>
<html>  
<head>

<title> Search by Development </title>
<meta http-equiv="Content-Type" content ="text/html; charset=iso-8859-1">
</head>


<body>
    <form name="form1" action="submit.php" method="post">
      <label type='text'> Name:</label>
      <select name ='userID'>
          <?php 
          $conn1 = new mysqli('localhost', 'root','','carpark_project'); 
          $result1 = $conn1->query("select userid from user");

          while($row =$result1->fetch_assoc())
          { ?>
          <option value="<? php echo $row['userid']; ?>">
              <?php echo $row['userid']; ?>
          </option>

          <?php
          } ?>

      </select>

      <br>

       <label type='text'> Development:</label>
      <select name ='Development'>
          <?php 
          $conn = new mysqli('localhost', 'root','','carpark_project'); 
          $result = $conn->query("select development from carpark");

          while($row =$result->fetch_assoc())
          { ?>
          <option value="<? php echo $row['development']; ?>">
              <?php echo $row['development']; ?>
          </option>

          <?php
          } ?>

      </select>
       <br>


<input type="submit" name="submit" value="submit"/>
</form>
</body>
</html>

以下是动作PHP文件。

<?php
 $con = new mysqli('localhost','root','','carpark_project');

$development = $_POST['Development'];
$userid = $_POST['userid'];

$inserthistory = "Insert into history (userid, development) values ('$userid','$development')";

  $result=mysqli_query($con,$inserthistory);

  if($result)
  {
    header("refresh:5; url=history.php");
  }
  else
  {
    echo "Not Updated";
  }

?>

请帮助,谢谢!

2 个答案:

答案 0 :(得分:1)

你有一个错字。它应该是$userid = $_POST['userID'];

此处也使用预备语句来防止sql注入攻击

$inserthistory = "Insert into history (userid, development) values (? , ?)"; #create sql string with placeholders to prevent sql injection
$sql = $con->prepare($inserthistory); #prepare the query.this line returns true or false 
$sql->bind_param('ss' , $userid, $development); #now specify that the variables are strings and then add the variables
if ($sql->execute() === true){ #execute it
#query successful 
} else {
#error
echo $con->error; 
}

也只是一个重要的观察。您应该有一个包含数据库连接的文件。目前,您正在为每个表单输入创建一个新的数据库连接,这是错误的。创建一个文件,然后在那里建立连接。然后,您所做的就是将文件包含在您需要的位置。

答案 1 :(得分:0)

<select name ='userID'>更改为<select name ='userid'>