1

I've just started to learn PHP. What I am trying to do a very simple sql select statement-

<?php
    $sql = 'SELECT firstname, lastname,email
           FROM MyGuests
          ORDER BY firstname where id=12';
?>

It gives the following error-

Could not connect to the database testdb :SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;

Sorry if it's a foolish question.

chris85
  • 23,846
  • 7
  • 34
  • 51
s.k.paul
  • 7,099
  • 28
  • 93
  • 168

3 Answers3

2

Switch the ORDER BY and WHERE clauses:

SELECT firstname,
       lastname,
       email
FROM MyGuests
WHERE id = 12
ORDER BY firstname

Here is a useful Stack Overflow question which lists the order of interpretation of a MySQL statement:

MySQL query / clause execution order

Community
  • 1
  • 1
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

Your query is in the wrong order, order by needs to be after the where.

SELECT firstname, lastname,email
           FROM MyGuests
          where id=12
ORDER BY firstname

You can see the order for all functions in the manual, http://dev.mysql.com/doc/refman/5.7/en/select.html.

chris85
  • 23,846
  • 7
  • 34
  • 51
1

You got the syntax wrong..

SELECT..
FROM..
WHERE..
GROUP BY..
ORDER BY ..

So:

SELECT firstname, lastname,email
FROM MyGuests
where id=12
ORDER BY firstname 
sagi
  • 40,026
  • 6
  • 59
  • 84