好的,所以我编写了一些代码来查找测试数据库中的记录,如果有记录并显示数据,它会起作用,如果没有记录,它仍然会说它找到了东西。应该说它没有。它甚至可以找到不在数据库中但显然没有数据要显示的东西,这很烦人。 我需要一双新眼睛。
我认为错误就在这里:
$sql = "SELECT * FROM Kittenzz
WHERE KittenID='".$_POST['KittenID']."';";
$result = mysql_query($sql, $connection);
但是,以防这里是完整代码减去db的登录凭据。
<?php
if(isset($_POST['Find']))
{
$connection = mysql_connect("Login Info Deleted");
// Check connection
if (!$connection)
{
echo "Connection failed: " . mysql_connect_error();
}
else
{ //else 1
//select a database
$dbName="Katz";
$db_selected = mysql_select_db($dbName, $connection);
//confirm connection to database
if (!$db_selected)
{
die ('Can\'t use $dbName : ' . mysql_error());
}
else
{ //else 2
if ($_POST[KittenID]=='')
{
$OutputMessage = 'Must add a Kitten-ID';
}
else
{//exception else
$sql = "SELECT * FROM Kittenzz
WHERE KittenID='".$_POST['KittenID']."';";
$result = mysql_query($sql, $connection);
while($row = mysql_fetch_array($result))
{
$Name = $row['Name'];
$KittenID = $row['KittenID'];
$KittenAge = $row['KittenAge'];
$Email = $row['Email'];
$Comments = $row['Comments'];
$Gender = $row['Gender'];
$Passive = $row['Passive'];
$Playful = $row['Playful'];
$Activity = $row['Activity'];
}
if ($result)
{
$OutputMessage = 'Record Found';
//echo "<p>Record found<p>";
}
else
{
$OutputMessage = 'RECORD NOT FOUND';
}
}//exception else
}//else 2 end
}//else 1 end
mysql_close($connection);
}
?>
答案 0 :(得分:3)
if ($result)
{
$OutputMessage = 'Record Found';
}
有错误,这意味着如果查询执行成功(即使有0条记录),您说的是找到的记录。您应该只说如果返回的记录数大于0。
if (mysql_num_rows($result)>0)
{
$OutputMessage = 'Record Found';
}
但是你的代码的更大问题可以通过这个阅读来解决
答案 1 :(得分:2)
这可能会发生,因为如果$_POST['KittenID']
为空,则sql查询看起来像:SELECT * FROM Kittenzz WHERE KittenID="";
您必须将上述if语句更改为:
if (!isset($_POST[KittenID]) || empty($_POST[KittenID]) || $_POST[KittenID]=='')
{
$OutputMessage = 'Must add a Kitten-ID';
}