使用BETWEEN进行PHP搜索无法正常工作

时间:2013-12-02 18:31:42

标签: php mysql

我创建了一个在两个条目之间搜索的两个字段。通过使用GET方法。

<form name="search">
  <input name="to" id="to" type="text" />
  <input name="end" id="end" type="text" />
  <input name="submit" id="submit" type="submit" />
</form>
<table border="1">
  <tr>
    <td>Name</td>
  </tr>
<?php

if(isset($_GET['submit'])){

$db_host="localhost";
$db_username="root";
$db_password="";
$db_name="administrator";
$db_tb_name="customer_details";
$db_tb_usr_name="name";
$db_tb_npkgr_name="no_of_pkg";

mysql_connect("$db_host","$db_username","$db_password");
mysql_select_db("$db_name");

$s_name=mysql_real_escape_string($_GET['to']);
$m_name=mysql_real_escape_string($_GET['end']);

$query_for_result = mysql_query("SELECT * FROM $db_tb_name WHERE 
$db_tb_npkgr_name BETWEEN '%".$s_name."%' AND '%".$m_name."%'");

while($data_fetch=mysql_fetch_array($query_for_result))
{
?>
  <tr>
    <td><?php echo substr($data_fetch[$db_tb_usr_name], 0,160); ?></td>
  </tr>
<?php } mysql_close(); }?>
</table>

在此代码中,输出显示什么,但是当我使用一个字段进行搜索时,它可以正常工作。

这是单一搜索的工作代码。我在这里使用LIKE运算符。

<form name="search">
  <input name="to" id="to" type="text" />
  <input name="submit" id="submit" type="submit" />
</form>
<table border="1">
  <tr>
    <td>Name</td>
  </tr>
<?php

if(isset($_GET['submit'])){

$db_host="localhost";
$db_username="root";
$db_password="";
$db_name="administrator";
$db_tb_name="customer_details";
$db_tb_usr_name="name";
$db_tb_npkgr_name="no_of_pkg";

mysql_connect("$db_host","$db_username","$db_password");
mysql_select_db("$db_name");

$s_name=mysql_real_escape_string($_GET['to']);

$query_for_result = mysql_query("SELECT * FROM $db_tb_name WHERE 
$db_tb_npkgr_name LIKE '%".$s_name."%'");


while($data_fetch=mysql_fetch_array($query_for_result))
{
?>
  <tr>
    <td><?php echo substr($data_fetch[$db_tb_usr_name], 0,160); ?></td>
  </tr>
<?php }
mysql_close(); }?>
</table>

这段代码很棒。但是当我使用BETWEEN时,它在输出中没有显示任何内容。 怎么了?解决方案是什么?

谢谢。

1 个答案:

答案 0 :(得分:3)

BETWEEN不像LIKE命令那样工作。您不能使用通配符(%)字符。尝试删除它们。