Into a MYSQL query, I am trying to insert a WHERE clause (the one that appears in the PHP comment below). Whenever I place this clause in the MYSQL query statement, it always fails (I’ve tried both before the LEFT JOIN and before the ORDER BY clauses).
Any ideas on how I can get my statement to work?
<?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'];
}
?>
SQL stands for Structured Query Language — you can’t put a WHERE clause wherever you want in the query. The WHERE clause has to be after the FROM/JOIN clauses, and before the GROUP BY, HAVING, and ORDER BY clauses. IE:
A better option, to insulate yourself from SQL injection attacks, is to use sprintf: