我在数据库中有一个表,有 3 列,第一列 id(PK),第二列 nameOfPerson 和第三列父列(外键)。当我在文本字段中输入姓名并从下拉列表中选择父级时,我想将 nameOfPerson 下的名称和父级下的父级插入数据库。为什么在我的代码中,当我单击“提交”时没有任何反应?
这是我的 table
id nameOfPerson parent
3 John NULL
4 Michel 3
5 Husam 4
6 Khalaf 5
7 Mark 5
----------------------------
这是我的功能来获取谁可以成为 parent
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>
最佳答案
您的查询失败,因为在您发送字符串时,parent
列需要是整数。
问题在于如何为 parent 输出选择框。
echo "<option>" .$output['nameOfPerson']."</option>";
如果您省略 value
属性,则将发送文本(在本例中为名称)。
添加 id
作为值,它应该可以工作:
echo "<option value='{$outout['id']}'>" .$output['nameOfPerson']."</option>";
现在将发送 ID 而不是名称。
关于php - 将带有下拉菜单的文本插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50665985/