php - Else and If mysql 和 php 错误

标签 php mysql

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

$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 注入(inject)!

使用 mysql_num_rows,您可以检查您的查询返回了多少行。你必须做一个查询来检查它。检查 $sql 变量是否为空是没有用的,因为它只是始终“完整”的字符串 - 它包含您的查询语句。

关于php - Else and If mysql 和 php 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9481868/

相关文章:

php - is_dir() 在 php 中扫描目录时失败

php - 中间的 nohup php 脚本 mysql 问题

java - 如何修复 “Incorrect string value for the column at the row 1”错误?

Mysql - 从 unix 时间戳中选择年份

php - Laravel 使用数据库数据填充表单但显示所有用户数据

php - 了解如何使用 AJAX 在 php 中与 smarty 一起工作

php - 保持数据分组,不按订单分隔

javascript - 在 WP 中使用 PHP 将 javascript 字符串插入 HTML

php 扩展但有一个新的构造函数......可能吗?

mysql - 如何在所有表和所有列中查找字符串?