我是 PHP 的新手,仍在学习它的语法。我刚刚完成了一个工作脚本,但我想添加一个条件来检查输入的关键字是否找到或未找到。我知道我需要使用 IF ELSE 但我不知道要在 () 中放什么。我在谷歌上搜索并看到了使用 if(!result) 解决方案来接收 true 或 false 返回值的示例,但它似乎不适用于我正在尝试做的事情。
希望对你有所帮助。所以我可以改进我的搜索脚本。提前致谢。 我会很感激最简单的条件/脚本。
<?php
include('databaseConnection.php');
?>
<?php
if(isset($_POST['userSearch']))
{
$keyword = $_POST['userSearch'];
$sql = " SELECT * FROM booklist WHERE (Title LIKE '%$keyword%' OR Author LIKE '%$keyword%' OR ISBN LIKE '%$keyword%' ) ";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
$title = $row['Title'];
$author = $row['Author'];
$yearLevel = $row['YearLevel'];
$isbn = $row['ISBN'];
echo "<table border = 1>" ;
echo "<th>Title </th>" ;
echo "<th> Author </th>" ;
echo "<th> Year Level </th>" ;
echo "<th> ISBN </th>";
echo "<tr>" ;
echo "<td>" .$title."</td> " ;
echo "<td>" .$author."</td> " ;
echo "<td>".$yearLevel."</td> " ;
echo "<td>" .$isbn. "</td> " ;
echo "</tr>" ;
echo "</table>" ;
echo "<br />" ;
echo "<a href='./menu.php'> Back to Home </a>" ;
}
} // end of Main IF
?>
最佳答案
您可以使用 mysql_num_rows()
查看您的 SELECT
查询是否返回任何结果。
if (mysql_num_rows($result)) // there are results
...
else // there are no results
...
来自手册:http://php.net/manual/en/function.mysql-num-rows.php
正如其他人所说,您应该避免使用 mysql
函数并移至 mysqli
或 PDO
。
关于用于验证是否找到搜索脚本的 PHP 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33498259/