php - SQL 语法错误,请检查与您的 MySQL 服务器版本对应的手册,以了解在第 1 行 'ORDER BY category ASC' 附近使用的正确语法

标签 php mysql sql select

网站多年来一直运行良好,突然我收到此错误。专家的任何帮助将不胜感激。

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER BY category ASC' at line 1

这是有问题的代码:

// SQL injection attack prevention function
$unit_Recordset1 = "";
if (isset($_GET['unit'])) {
  $unit_Recordset1 = GetSQLValueString($_GET['unit'], "text");
}
$category_Recordset1 = "";
if (isset($_GET['category'])) {
  $category_Recordset1 = GetSQLValueString($_GET['category'], "text");
}
else $_GET['category'] = "";

// Query builder that create single or multiple AND query
$sql = "SELECT * FROM documents WHERE ";
if(!empty($unit_Recordset1)) {$sql .= " unit = $unit_Recordset1 AND ";}
if(!empty($category_Recordset1)) {$sql .= " category = $category_Recordset1 AND ";}
// Remove the last AND
$sql = substr($sql, 0, -4);
if(!empty($category_Recordset1)) $sql .= " ORDER BY title ASC";
else $sql .= " ORDER BY category, title ASC";


// Query for left nav DISTINCT category values
$sqlnav = "SELECT DISTINCT category FROM documents WHERE unit = $unit_Recordset1 ORDER BY category ASC";


mysql_select_db($database_local, $local);

$Recordset1 = mysql_query($sql, $local) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);

$Recordset2 = mysql_query($sqlnav, $local) or die(mysql_error());
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
$totalRows_Recordset2 = mysql_num_rows($Recordset2);

最佳答案

在某些流中,$unit_Recordset1 可能为空。在这种情况下,声明如下:

$sqlnav = "SELECT DISTINCT category FROM documents WHERE unit = $unit_Recordset1 ORDER BY category ASC";

将评估为:

SELECT DISTINCT category FROM documents WHERE unit = ORDER BY category ASC

这当然不是有效的 SQL。 您还需要针对这种情况添加检查,如下所示:

$unitClause = "";
if(!empty($unit_Recordset1) {
    $unitClause = "WHERE unit = $unit_Recordset1 ";
}
$sqlnav = "SELECT DISTINCT category FROM documents $unitClause ORDER BY category ASC";

关于php - SQL 语法错误,请检查与您的 MySQL 服务器版本对应的手册,以了解在第 1 行 'ORDER BY category ASC' 附近使用的正确语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27499402/

相关文章:

sql - postgresql - 通过更改 id 和 parent_id 使用同一表中的行更新树表

PHP 脚本在您手动启动时完成,但在通过 cronjob 启动时则不会

php - Laravel 5 预加载 belongsTo 关系

php - 获取上传的图像宽度和高度以加载实际图像大小

php - Laravel save() 方法后无法检索自定义 id 主键

mysql - 如何添加 SELECT 语句结果?

PHP:使用方法作为回调

MySQL - 更新日期/时间 - 10 分钟。在未来

mysql - 为什么在查询语句中添加group by后结果顺序发生了变化?

mysql - SQL计算几个不同组中的项目数量