日期:2014-05-17  浏览次数:20480 次

为什么连接了mysql却查询不了
表单页代码:
PHP code
<html>
<head>catalog search</head>
<body>
<h1>catalog search</h1>
<form action="results.php" method="post">
choose search type:<br/>
<select name="searchtype">
<option value="author">author</option>
<option value="title">title</option>
<option value="isbn">isbn</option>

</select>
<br/>
enter search term:<br/>
<input name="searchterm" type="text" size="40"/>
<br/>
<input  type="submit" name="submint" value="search"/>
</form>
</body>

</html>


PHP code
<html>
<body>
<h1>search results</h1>
<?php
$searchtype=$_POST['searchtype'];
$searchterm=trim($_POST['searchterm']);
if(!$searchtype||!$searchterm){
    echo"请输入值";
        exit;

}
if(!get_magic_quotes_gpc())
{
    $searchtype=addslashes($searchtype);
    $searchterm=addslashes($searchterm);
}
@ $db=new mysqli('localhost','root','root','books');
if (mysqli_connect_errno()) 
{
echo 'Error: Could not connect to database. Please try again later.';
exit;
}

$query="select * from books where".$searchtype."like '%".$searchterm."%'";
$result=$db->query($query);
$num_results=$result->num_rows;
echo "<p>Number of books found:".$num_results."</p>";
for ($i=0;$i<$num_results;$i++)
{
    $row=$result->fetch_assoc();
    echo"<p><strong>".($i+1)."title:";
    echo htmlspecialchars(stripslashes($row['title']));
    echo "</strong><br/>author:";
    echo stripslashes($row['author']);
    echo"<br/>isbn:";
    echo stripslashes($row['isbn']);
    echo"<br/>price:";
    echo stripslashes($row['price']);
    echo"</p>";
}
?>
</body>
</html>


输出结果:

search results
Number of books found:

为什么查询不出结果

------解决方案--------------------
你没有在执行查询后进行检错,应补上
1、确认 $searchtype 是正确的字段名
2、$query="select * from books where".$searchtype."like '%".$searchterm."%'";
中 like 前少了个空格
写成这样是不是清爽些?
$query = "select * from books where $searchtype like '%$searchterm%'";


------解决方案--------------------
$query="select * from books where".$searchtype."like '%".$searchterm."%'";
echo $query;就知道是否等价了。 红字部分连在一起了还对吗?
------解决方案--------------------
$query="select * from books where".$searchtype."like '%".$searchterm."%'";
$query = "select * from books where $searchtype like '%$searchterm%'";
这两个sql是有区别的。
""里面的都是字符串,然后你没有空格直接写.$searchtype。。。。你自己想想结果一样吗?