对于单一作业,我必须创建一个网页,用户可以回答是/否问题,系统会猜测他们正在考虑的动物。数据库必须是自引用表/二进制树。
我已经构建了似乎运行正常的数据库。
列是
nodeID,parentID,message,answerYesID,answerNoID。 parentID和两个answerId都是fk引用nodeID。
使用PHP我创建了按钮和一个检索第一个节点并询问第一个问题的函数。我已经到了系统要求下一个适当问题的地步。这是我被困的地方。我已经尝试了各种切换方式和if语句,但我正在努力正确遍历二叉树。
我创建了一个变量$ currentnode,我将用它来跟踪用户的位置,以便可以提出正确的问题,但是,在下一个if块中使用它会导致系统向前跳。
非常感谢任何帮助
$query = "SELECT `message`, `nodeID` FROM `creature`";//basic query that will be used at all times
$where = "";//empty where clause, will be altered
//function created to be re used after an answer is given
function output($query,$where,$dbconn){
$result = mysqli_query($dbconn, $query.$where);
while($row = mysqli_fetch_assoc($result))
echo "{$row['message']}
{$row['nodeID']}<br>";
echo '<form action="play.php" method="POST">
<input type="radio" name="answer" value="1">yes
<input type="radio" name="answer" value="0">no
<input type = "submit" name = "submit" value = "submit">
<input type = "submit" name = "restart" value = "restart game">
</form>';}
?>
<form action="play.php" method="POST">
<input type="submit" name="start" value="Start Game">
</form>
<?php
if ( isset( $_POST['start'] ))
{
$where = "WHERE `nodeID` = '1'";
$currentnode = '1';
output($query,$where,$dbconn);
}
if ($currentnode = 1){
if ( isset( $_POST['submit'] )){
switch ($_POST['answer']) {
case 1: $where = "WHERE `nodeID` = '2'";
output($query,$where,$dbconn);
$currentnode = 2;
break;
case 0: $where = "WHERE `nodeID` = '25'";
output($query,$where,$dbconn);
$currentnode = 25;
break;
}
}
}
if ($currentnode = 2){
if ( isset( $_POST['submit'] )){
switch ($_POST['answer']) {
case 1: $where = "WHERE `nodeID` = '3'";
output($query,$where,$dbconn);
$currentnode = 3;
break;
case 2: $where = "WHERE `nodeID` = '4'";
output($query,$where,$dbconn);
$currentnode = 4;
break;
}
}
}
if ( isset( $_POST['restart'] ))
{
$where = "WHERE `nodeID` = '1'";
output($query,$where, $dbconn);
}