在db中插入带有下拉列表的文本

flseospp  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(338)

我在数据库中有一个表,它有3列,第一列id(pk),第二列人名和第三列父项(外键)。当我在文本字段中输入name并从下拉列表中选择parent时,我想在db中插入nameofperson下的name和parent下的parent。为什么在我的代码中,当我点击提交时什么都没发生?
这是我的table

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>
kmbjn2e3

kmbjn2e31#

查询失败,因为列 parent 发送字符串时必须是整数。
问题是如何为父母输出selectbox。

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

如果你忽略了 value -属性,则改为发送文本(在本例中为名称)。
添加 id 作为价值,它应该起作用:

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

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

相关问题