php简单搜索mysql不显示数据
<?php$con=mysql_connect("localhost","root","root");if(!$con){die('Couldnotconnect:'.m...
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dingcan", $con);
$searchs = $_POST['search']; //传递search框过来的值
$searchs= trim($searchs);
if (!$searchs)
{
echo '搜索框不能为空.';
exit;
}
$result = mysql_query("SELECT * FROM kj_meal_shop where shop_name like
'%$searchs%'");
if (mysql_num_rows($result) < 1) echo '没有数据';
while($row = mysql_fetch_array($result))
{
echo $row['shop_id'] . " " . $row['shop_name'];
echo "<br />";
}
mysql_close($con);
?>
代码是PHP简单搜索页的代码,图片是myadmin的截图,搜索代码中的POST值是有收到的,但是运行结果显示没有数据,但是在myadmin搜索的话是有数据的,不知我的代码那个步骤有错,望高手指教 展开
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dingcan", $con);
$searchs = $_POST['search']; //传递search框过来的值
$searchs= trim($searchs);
if (!$searchs)
{
echo '搜索框不能为空.';
exit;
}
$result = mysql_query("SELECT * FROM kj_meal_shop where shop_name like
'%$searchs%'");
if (mysql_num_rows($result) < 1) echo '没有数据';
while($row = mysql_fetch_array($result))
{
echo $row['shop_id'] . " " . $row['shop_name'];
echo "<br />";
}
mysql_close($con);
?>
代码是PHP简单搜索页的代码,图片是myadmin的截图,搜索代码中的POST值是有收到的,但是运行结果显示没有数据,但是在myadmin搜索的话是有数据的,不知我的代码那个步骤有错,望高手指教 展开
1个回答
展开全部
'%$searchs%' 会在变量前生成一个空格 ,LIKE严格匹配格式 这个空格导致你搜索不到东西。
要用$sql ="("SELECT * FROM kj_meal_shop where shop_name like";
用类似 $sql = $sql." ".'\''.str_replace(" ","","%,$searchs%").'\'';
str_replace()空字符替换掉空格 才能执行
要用$sql ="("SELECT * FROM kj_meal_shop where shop_name like";
用类似 $sql = $sql." ".'\''.str_replace(" ","","%,$searchs%").'\'';
str_replace()空字符替换掉空格 才能执行
追问
用不到,这个是'%$searchs%'是怎么用的?能告诉我改哪里吗
$sql = $sql." ".'\''.str_replace(" ","","%,$searchs%").'\'';
这个语句加在哪里?
追答
$sql = $sql." ".'\''.str_replace(" ","","%,$searchs%").'\'';
这句话的意思就是在"("SELECT * FROM kj_meal_shop where shop_name like 的后面加上去掉空格的%$searchs%啊
你如果直接写在一起 他编译过来 %(多一个空格) 变量% 的导致你查找不到,所以要加str_replace把空格去掉
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询