查询无效:SQL语法中存在错误;语法在附近使用

时间:2015-11-01 12:44:09

标签: php mysql sql syntax executequery

我有这个问题错误,我不知道如何解决它。我知道有很多问题像我的问题一样,但我无法定位。

问题:

Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM `user` WHERE `id` = 0' at line 6

代码:

<?php
function fetch_users(){
$result = mysql_query('SELECT `id` AS `id`, `username` AS `username` FROM `user`');

$users = array();

while(($row = mysql_fetch_assoc($result)) !== false){
       $users[] = $row;
   }

   return $users;

}

// fetches profile information for the given user.
function fetch_user_info($id){
   $id = (int)$id;

   $sql = "SELECT 
               `username` AS `username`,
               `firstname` AS `firstname`,
               `lastname` AS `lastname`,
               `email` AS `email`,
             FROM `user` WHERE `id` = {$id}";

      $result = mysql_query($sql);
      if (!$result) {
   die('Invalid query: ' . mysql_error());
   }

      return mysql_fetch_assoc($result);
}


?>

2 个答案:

答案 0 :(得分:4)

删除最后一栏后的逗号:

$sql = "SELECT 
             `username` AS `username`,
             `firstname` AS `firstname`,
             `lastname` AS `lastname`,
             `email` AS `email`              -- here
         FROM `user` WHERE `id` = {$id}";

此外,您不需要使用与列相同的别名:

$sql = "SELECT 
             `username`,
             `firstname`,
             `lastname`,
             `email`  
         FROM `user` WHERE `id` = {$id}";

答案 1 :(得分:0)

问题在于$sql中sql查询的语法形成,因为错误本身告诉错误在FROM user WHERE id=0附近,comma ,附近email附近在select查询中抛出sql错误。

<?php
echo 'test';

function fetch_users(){
    $result = mysql_query('SELECT `id` AS `id`, `username` AS `username` FROM `user`');
    $users = array();
    while(($row = mysql_fetch_assoc($result)) !== false){
        $users[] = $row;
    }
    return $users;
}
// fetches profile information for the given user.
function fetch_user_info($id){
    $id = (int)$id;
    $sql = "SELECT 
`username` AS `username`,
`firstname` AS `firstname`,
`lastname` AS `lastname`,
`email` AS `email`
FROM `user` WHERE `id` = {$id}";
    $result = mysql_query($sql);
    if (!$result) {
        die('Invalid query: ' . mysql_error());
    }
    return mysql_fetch_assoc($result);
}
echo fetch_users();

?>