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,591
  • 7
  • 30
  • 47
s.k.paul
  • 6,663
  • 24
  • 88
  • 159

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
  • 451,927
  • 24
  • 239
  • 318
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,591
  • 7
  • 30
  • 47
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
  • 38,630
  • 5
  • 53
  • 82