Else和If mysql和php错误


Else and If mysql and php error

当一些数据不存在时,我想返回一个不可用的,但我认为我的代码中有问题

$id=$_GET["id"];
$sql="SELECT * FROM book WHERE id = '".$id."' AND type = 'new'";
if(!empty($sql))
{
    $result = mysql_query($sql);
    $row = mysql_fetch_assoc($result); 
    echo utf8_encode($row['bookreview']);
}
else
{
    echo "<div style='text-align: center; background-color: rgb(255, 255,255);'><font style='color: rgb(204, 0, 0);' size='+3'><span style='font-weight: bold;'>review not not available.</span></font><br>";
}

如果审查可用,则返回审查,而如果不可用,则不会回复"审查不可用"。

$id  = (int) $_GET['id']; // important !
$sql = 'SELECT * FROM book WHERE id = ' . $id. ' AND type = "new"';
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
    $row = mysql_fetch_assoc($result); 
    echo utf8_encode($row['bookreview']);
} else {
    echo "<div style='text-align: center; background-color: rgb(255, 255,255);'><font style='color: rgb(204, 0, 0);' size='+3'><span style='font-weight: bold;'>review not not available.</span></font><br>";
}

将GET参数强制转换为指定类型(此处为int)以避免SQL注入非常重要!

使用mysql_num_rows,您可以检查查询返回了多少行。你必须进行查询才能检查它。检查$sql变量是否为空是没有用的,因为它只是一个总是"满"的字符串——它包含你的查询语句。

$sql变量包含一个字符串,该字符串是在检查是否为空之前指定的。在这种情况下,它永远不会是空的。

也许您要做的是检查查询返回的结果数?为了实现这一点,您必须首先运行查询。下面是一个关于mysqli的快速示例:

$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");
$id = $_GET["id"];
$sql = "SELECT * FROM book WHERE id = '".$id."' AND type = 'new'";
// Run query
if ( $result = $mysqli->query($sql) )
{
   // We got results
   var_dump($result);
   $result->close();
}
else
{
   // No results
   echo("Oops. Nothing here.");
}

为了避免SQL注入,我建议学习PDO以及如何编写准备好的语句。

您实际上是在检查字符串是否为空,而不是结果集,看到了吗?

!empty("any string")

将始终返回true。

$sql永远不会为空。。因为是一个你刚刚设置的字符串。你可能想做:

$id=$_GET["id"];
$sql="SELECT * FROM book WHERE id = '".intval($id)."' AND type = 'new'";
$result = mysql_query($sql);
if(!empty($result) and mysql_num_rows($result) > 0)
{
    $row = mysql_fetch_assoc($result); 
    echo utf8_encode($row['bookreview']);
}
else
{
    echo "<div style='text-align: center; background-color: rgb(255, 255,255);'><font style='color: rgb(204, 0, 0);' size='+3'><span style='font-weight: bold;'>review not not available.</span></font><br>";
}