用户点击时PHP提交按钮

时间:2012-05-08 03:00:38

标签: php html form-submit

点击提交后我想收到多个请求。这意味着在我点击提交并获得结果后,我想再次查询结果并再次点击提交。我不想让自己回到虚无。

 <?php
 error_reporting(0);
 if (!$_POST['submit'])
 {
 <form action="http://localhost/test.php" method="post">
 Type of Leave: 
 <select name="leave">
 <option value=""selected="selected"></option>
 <option VALUE="Medical Leave"> Medical Leave</option>
 <option VALUE="Unpaid Leave"> Unpaid Leave</option> 
 </select>
 <input type="submit" name="submit" value="Check!" />
 </form>
 <?php
 }
 else
 {
 $conn=odbc_connect("employee","","") or die (odbc_errormsg());
 if (!$conn)  
 {
 exit
 ("Connection Failed: " . $conn);
 }
 else
 {
 $choice = $_POST['leave'];
 $sql="SELECT * FROM balance WHERE ID=$username";
 $rs=odbc_exec($conn,$sql);
 ?>
 <?php
 while (odbc_fetch_row($rs))
 {
 $choice=odbc_result($rs,"$choice");
 echo "<tr><td>$choice</td>";
 }
 odbc_close($conn);
 echo "</table>";
 }
 }

目前,代码本身会查询我想要的预期输出,但唯一的缺点是它会作为输出保留在那里。我的目标是让提交和选择选项留在那里,以便我可以继续输出我想要的结果,谢谢。

1 个答案:

答案 0 :(得分:0)

最佳用户体验是使用AJAX根据下拉列表中选择的内容动态更改结果表。对于更简单的解决方案,您可以尝试将表单向上移出if / else循环。首先放置表单,然后在表单打印后,检查if ($_POST['submit'])

在这个例子中,我还添加了一个小函数来将selected="selected"添加到为此提交选择的任何选项中。这很粗糙,但你明白了。

<?php
function matchPost($name,$val) {
if($val == $name)
    echo 'selected="selected"';
}
?>

<form action="http://localhost/test.php" method="post">
 Type of Leave: 
 <select name="leave">
 <option value=""></option>
 <option <?php matchPost('Medical_Leave',$_POST['leave']); ?> VALUE="Medical_Leave"> Medical Leave</option>
 <option <?php matchPost('Unpaid_Leave',$_POST['leave']); ?> VALUE="Unpaid_Leave"> Unpaid Leave</option> 
 </select>
 <input type="submit" name="submit" value="Check!" />
 </form>

<?php
 if ($_POST['submit'])

 {
 $conn=odbc_connect("employee","","") or die (odbc_errormsg());
 if (!$conn)  
 {
 exit
 ("Connection Failed: " . $conn);
 }
 else
 {
 $choice = $_POST['leave'];
 $sql="SELECT * FROM balance WHERE ID=$username";
 $rs=odbc_exec($conn,$sql);
 ?>
 <?php
 while (odbc_fetch_row($rs))
 {
 $choice=odbc_result($rs,"$choice");
 echo "<tr><td>$choice</td>";
 }
 odbc_close($conn);
 echo "</table>";
 }
 }