我编写了一个从数据库中输出动物名称的程序。但是我遇到了一个问题,即我的程序在找不到正确的值(不在数据库中的值)时无法执行该案例
<?php
$host='localhost';
$user='root';
$password='root';
$dbname='pet';
$connect=mysqli_connect($host,$user,$password,$dbname) or die("can not connect to server");
if(@$_GET['data']=='yes')
{
$animalName=trim($_POST['animal']);
$query="SELECT name FROM display WHERE name='$animalName'";
$result=mysqli_query($connect,$query) or die("can not execute query");
while($row=mysqli_fetch_assoc($result))
{
extract($row);
if(!$name==$animalName)
{
echo "not found";
}
else
{
echo "Hello $name. Have a nice day.";
}
}
}
else
{
echo "<form action='$_SERVER[PHP_SELF]?data=yes' method='POST'>
<h4>type an animal name in the box below and press enter</h4>
<p><input type='text' name='animal' maxlength='20'></p>
<p><input type='submit' value='submit'></p>
</form>";
}
?>
当我输入数据库中不存在的动物时,我的代码无法执行此块(它转到一个空页面)
if(!$name==$animalName)
{
echo "not found";
}
有什么解决方案吗?
如果未从数据库中获取结果集中的任何行,则 while 循环中的代码将永远不会执行。
您可能需要做的是在尝试进入 while 循环之前检查结果集中的行数。 如果您有 0 行,只需发出消息,不要尝试在 while 循环中从数据库"获取"任何结果。
在 while 循环之前使用 mysqli_num_rows()
<?php
$host = 'localhost';
$user = 'root';
$password = 'root';
$dbname = 'pet';
$connect = mysqli_connect($host, $user, $password, $dbname) or die("can not connect to server");
if (@$_GET['data'] == 'yes') {
$animalName = trim($_POST['animal']);
$query = "SELECT name FROM display WHERE name='$animalName'";
$result = mysqli_query($connect, $query) or die("can not execute query");
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
if (!$name == $animalName) {
echo "not found";
} else {
echo "Hello $name. Have a nice day.";
}
}
} else
echo "data not found";
} else {
echo "<form action='$_SERVER[PHP_SELF]?data=yes' method='POST'>
<h4>type an animal name in the box below and press enter</h4>
<p><input type='text' name='animal' maxlength='20'></p>
<p><input type='submit' value='submit'></p>
</form>";
}
?>
试试这个:
if ($name != $animalName) {
您的查询也容易受到 sql 注入的影响。
> 当 SELECT 由于数据库中没有动物而失败时,您缺少对 mysql_query() 返回任何行的检查。在 $result = mysqli_query($connect,$query) 语句后添加以下内容:
$result = mysqli_query($connect,$query);
if (mysql_num_rows($result) == 0) {
echo "not found";
}