进入MYSQL查询,我试图插入一个WHERE子句(下面的PHP注释中出现的子句)。每当我将此子句放在MYSQL查询语句中时,它总是失败(我在LEFT JOIN之前和ORDER BY子句之前都尝试过)。
关于如何让我的陈述发挥作用的任何想法?
<?php
$result = mysql_query("SELECT *
FROM Items
LEFT JOIN Topics on Topics.TopicID = Items.FK_TopicID
ORDER BY TopicSort, TopicName ASC, ItemSort, ItemTitle");
/* WHERE FK_UserID=$_SESSION[user_id] */
$topicname = false;
while($row = mysql_fetch_array($result)) {
if (!$row['TopicID']) {
$row['TopicName'] = 'Sort Me';
}
if ($topicname != $row['TopicName']) {
echo '<ul><li>' . $row['TopicName'] . '</li><ul>';
$topicname = $row['TopicName'];
}
echo '';
echo '<li>' . $row['ItemTitle'] . '</li>';
echo '';
}
if ($topicname != $row['TopicName']) {
echo '</ul>';
$topicname = $row['TopicName'];
}
?>
答案 0 :(得分:6)
SQL代表结构化查询语言 - 您不能在查询中的任何位置放置WHERE子句。 WHERE子句必须位于FROM / JOIN子句之后,以及GROUP BY,HAVING和ORDER BY子句之前。 IE:
SELECT *
FROM ITEMS i
LEFT JOIN TOPICS t ON t.TopicID = i.FK_TopicID
WHERE FK_UserID = $_SESSION[user_id]
ORDER BY TopicSort, TopicName ASC, ItemSort, ItemTitle
更好的选择是使用sprintf:
,以使自己免受SQL注入攻击$sql = sprintf("SELECT *
FROM ITEMS i
LEFT JOIN TOPICS t ON t.TopicID = i.FK_TopicID
WHERE FK_UserID = %u
ORDER BY TopicSort, TopicName ASC, ItemSort, ItemTitle",
mysql_real_escape_string($_SESSION[user_id]));
$result = mysql_query($sql);
答案 1 :(得分:1)
将WHERE子句放在ORDER BY子句之前。 http://dev.mysql.com/doc/refman/5.0/en/join.html
"SELECT * FROM Items LEFT JOIN Topics on Topics.TopicID = Items.FK_TopicID WHERE whateverTableTheFK_UserIDColumnIs.FK_UserID='".$_SESSION['user_id']."' ORDER BY TopicSort, TopicName ASC, ItemSort, ItemTitle"