【发布时间】:2018-11-12 22:15:31
【问题描述】:
我在数据库中有一个表,它有 3 列,第一列 id(PK),第二列 nameOfPerson 和第三列 parent(外键)。当我在文本字段中输入名称并从下拉列表中选择父级时,我想将 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>
【问题讨论】:
-
您是否从您的
enterChild()方法中收到任何消息?你做过调试吗?检查代码中不同阶段的值,看看你得到了什么以及方法是否被调用等? -
您还应该为您的查询添加一些适当的错误处理:php.net/manual/en/pdostatement.errorinfo.php
-
是的,他得到了方法并回显错误@MagnusEriksson
-
然后添加错误处理(我的第二个链接)以找出查询是否由于某种原因失败。
-
现在它的工作......非常感谢您,先生。