使用下拉列表将文本插入数据库

时间:2018-06-03 11:40:24

标签: php mysql oop pdo

我在数据库中有3列的表,第一列id(PK),第二列nameOfPerson和第三列parent(foriegn key)。当我在文本字段中输入名称并从下拉列表中选择父项时,我想在DB中插入nameOfPerson下的名称和父项下的父项。为什么在我点击时我的代码中没有提交任何内容?

这是我的表

id  nameOfPerson    parent
3   John             NULL
4   Michel            3
5   Husam             4
6   Khalaf            5
7   Mark              5
---------------------------- 

这是我的职责,可以让谁成为父母

    public function displayParent(){
     //$statment = $this->db->prepare("SELECT DISTINCT  person.nameOfPerson, b.nameOfPerson as name FROM person LEFT JOIN person b ON (person.parent = b.id)");
        $statment = $this->db->prepare("SELECT id, nameOfPerson FROM person");
        $statment->execute();
        $result = $statment->fetchAll();
        foreach($result as $output){
            echo "<option>" .$output['nameOfPerson']."</option>";
        }
 }

这是我将数据插入数据库的功能

    public function enterChild(){

        $statment = $this->db->prepare("INSERT INTO person (nameOfPerson, parent) VALUES(:name, :parent)");
        $statment->bindParam(':name',$_POST['name']);
        $statment->bindParam(':parent',$_POST['parent']);
        $statment->execute();
        $result = $statment->rowCount();
        if($result == "1")
        {
            $message = '<label>successfully</label>';
        }
            else
            {
                $message = '<label>Wrong</label>';
            }
    echo $message;
 }

这是mu索引代码

<?php include_once('Family.php');
$object = new Family();
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Family Tree</title>
</head>
<body>
<form method="post">
  Child Name: <input type ='text' name ='name' placeholder="Enter name here">
  <select name="parent" id="names" onchange="getSelectValue()">
  <option>--Select Parent--</option>
  <?php echo $object->displayParent() ?>
  </select>
    <br>
    <input type="submit" name="submit" value="Enter">
</form>

<script>
    //Get selected nema
    function getSelectValue(){

        var selectedValue = document.getElementById("names").value;
        console.log(selectedValue);
    }
</script>

<?php
    $object->GetFamilyTree();
    if(isset($_POST['submit'])){

        $name=  $_POST["name"];
        $parent= $_POST["parent"];
        $object->enterChild();
    }
?>


</body>
</html>

1 个答案:

答案 0 :(得分:1)

您的查询失败,因为当您发送字符串时,列parent需要是一个整数。

问题是你如何输出父母的选择框。

echo "<option>" .$output['nameOfPerson']."</option>";

如果省略value - 属性,则会发送文本(在本例中为名称)。

添加id作为值,它应该有效:

echo "<option value='{$outout['id']}'>" .$output['nameOfPerson']."</option>";

现在将发送id而不是名称。