SQLSTATE[42000]:语法错误或访问冲突:sql select 语句中的 1064

SQLSTATE[42000]: Syntax error or access violation: 1064 in sql select statement

我刚开始学习PHP。我正在尝试做一个非常简单的 sql select 语句-

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

它给出了以下错误-

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

抱歉,如果这是一个愚蠢的问题。

您的查询顺序错误,order by 需要在 where 之后。

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

您可以在手册中查看所有功能的顺序,http://dev.mysql.com/doc/refman/5.7/en/select.html

切换 ORDER BYWHERE 子句:

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

这是一个有用的 Stack Overflow 问题,其中列出了 MySQL 语句的解释顺序:

MySQL query / clause execution order

你语法错误..

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

所以:

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