如何获取下拉列表值并将其插入MySQL服务器?

时间:2019-04-17 14:29:35

标签: php html mysql

声明

我想使用PHP文件从main.php文件中的下拉列表中的值获取MySQL服务器。

条件

如果用户未选择任何选项或未选择默认选项<option value="0">(Select Animal)</option>,其中选项值=0。

然后,如果选项值= 0,则下拉列表中的值不应插入MySQL服务器。

那么,我需要在add.php中添加什么?

main.php

<html>
<?php
include 'connection.php';
require_once 'add.php';
?>
<body>
<form method="post" action="add.php">
     <select id="animal" name="animal">                      
            <option value="0">(Select Animal)</option> <!--Non select option-->
            <option value="Cat">Cat</option>
            <option value="Dog">Dog</option>
            <option value="Cow">Cow</option>
     </select>
     <button type="submit" name="Save">Save</button > <!--Send the selected value to add.php-->
</form>
</body>
</html>

另一个PHP文件(add.php)

<?php

include 'connection.php';
if(isset($_POST['Save']))
      {
              $animal = mysqli_real_escape_string($conn,$_POST['animal']; );            
              $conn->query("INSERT INTO animal (name) VALUES(?)");              
              header("location: main.php");
      }
?>

3 个答案:

答案 0 :(得分:1)

在检查数组键是否已设置之前,请确保您知道该数组键存在,否则可能会收到错误/警告。

然后确保动物值大于0 ...并将其包含在查询中。

<?php
    include 'connection.php';
    if(array_key_exists('Save', $_POST)) {
      if(array_key_exists('animal', $_POST) && $_POST['animal'] > 0) {
        $animal = mysqli_real_escape_string($conn, $_POST['animal']);

        //Prepare statement
        $conn->prepare("INSERT INTO animal (name) VALUES (?)");

        //Include animal value in string query
        $conn->bind_param("s", $animal);

        //Run query
        $conn->query($sql);    

        header("location: main.php");
      } else {
        //Fail gracefully
        header("location: error.php"); //Or whereever you want to redirect to.
      }  
    }
    ?>

请记住,您实际上并未在此处运行查询。

您只是将其创建为字符串,也没有在其上添加animal的值。

另外,在执行$_POST['animal']时,请删除mysqli_real_escape_string()之后的分号。

编辑:我已经用您的更新更新了我的

编辑2:我还添加了正确准备语句所需的内容。

答案 1 :(得分:1)

从@sony的答案中,我将if($_POST['animal']!= 0)更改为if($_POST['animal']!= '0')以使其起作用。

更改

  • 添加了两个单引号。
<?php

include 'connection.php';
if(isset($_POST['Save']))
{
 if($_POST['animal']!= '0') //2 Single quotes are added.
{
              $animal = mysqli_real_escape_string($conn,$_POST['animal']);            
              $sql="INSERT INTO animal (name) VALUES(?) ";              
              header("location: main.php");
    }else{ 
      header("location: main.php");
    }
      }
?>

答案 2 :(得分:0)

您可以对下拉菜单使用Javascript验证,也可以为动物的$ _POST保留条件,如下所示:

<?php

include 'connection.php';
if(isset($_POST['Save']))
      {
 if($_POST['animal']!=0){
              $animal = mysqli_real_escape_string($conn,$_POST['animal']);            
              $sql="INSERT INTO animal (name) VALUES(?) ";              
              header("location: main.php");
    }else{ 
      header("location: main.php");
    }
      }
?>