PHP - 我重新加载页面后仍会显示搜索结果

时间:2016-05-01 12:51:49

标签: php

我想知道在用户刷新页面后我的搜索结果仍然显示的原因以及我如何解决它。 PHP代码:

$con = mysql_connect($db_hostname,$db_username,$db_password);
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db($db_database, $con);

if (!empty($_REQUEST['term'])) {

$term = mysql_real_escape_string($_REQUEST['term']);     

$sql = "SELECT * FROM FUMUKU WHERE TimeD LIKE '%".$term."%'"; 
$r_query = mysql_query($sql); 

while ($row = mysql_fetch_array($r_query)){  
echo '<br /> Stock: ' .$row['Stock'];  
echo '<br /> Price: ' .$row['Price'];  
echo '<br /> Time: '.$row['TimeD'];   
}  

HTML代码:

<form action="" method="post">  
Search: <input type="text" name="term" /><br />  
<input type="submit" value="Submit" />  
</form>  

1 个答案:

答案 0 :(得分:1)

您的PHP脚本在页面加载时执行。为防止这种情况发生,您需要在PHP代码的顶部添加if(isset($_POST['submit'])) {并将name="submit添加到提交按钮。

<?php 
$con = mysql_connect($db_hostname,$db_username,$db_password);
if (!$con) {
 die('Could not connect: ' . mysql_error());
}

if(isset($_POST['submit'])) {
if (!empty($_REQUEST['term'])) {

$term = mysql_real_escape_string($_REQUEST['term']);     

$sql = "SELECT * FROM FUMUKU WHERE TimeD LIKE '%".$term."%'"; 
$r_query = mysql_query($sql); 

while ($row = mysql_fetch_array($r_query)){  
echo '<br /> Stock: ' .$row['Stock'];  
echo '<br /> Price: ' .$row['Price'];  
echo '<br /> Time: '.$row['TimeD'];   
}  
}
}  
?>

<form method="post">  
Search: <input type="text" name="term" /><br />  
<input type="submit" name="submit" value="Submit" />  
</form>