0

How can I add ORDER BY field to the end of this SQL query $sql = "SELECT item_id,field FROM item WHERE department=".$catid;? I can't get the syntax right due to the PHP variable at the end...

I tried $sql = "SELECT item_id,field FROM item WHERE department=".$catid ORDER BY field; but obviously that didn't work

7
  • Please show what you've tried. Variables don't go in SQL, parameterize your query. Commented Apr 2, 2020 at 2:00
  • 1
    ORDER BY field is an obvious syntax error. Are you using error reporting? It is the same as you wrote your other string encapsulation, "SELECT ... BUT realllly you shouldn't be doing this at all. The query should be SELECT item_id,field FROM item WHERE department= ? ORDER BY field then bind $catid. Commented Apr 2, 2020 at 2:02
  • @user3783243 Sorry, I don't know much more SQL... What would be the best practice way of doing this? Commented Apr 2, 2020 at 2:04
  • It's PHP syntax, not SQL. The SQL is "right" if $catid is an integer. Commented Apr 2, 2020 at 2:04
  • I don't know what driver your using with PHP so I can't tell you but look up prepared statements with the driver you are using. Commented Apr 2, 2020 at 2:13

1 Answer 1

1

You can fix your syntax error like this, using another concatenation operator . to append the ORDER BY clause:

$sql = "SELECT item_id,field FROM item WHERE department=".$catid." ORDER BY field";

As long as $catid is an integer, that will work, but it may leave you open to SQL injection, dependent on the source of the value in $catid.

Best practice is to use a prepared query. For MySQLi, something like this:

$sql = "SELECT item_id,field FROM item WHERE department=? ORDER BY field";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $catid);  // change to 's' if $catid is a string
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // do something with results
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.