2

I have this problem error and I don't know how to solve it. I know what so many have issues like my issue but I can not orient.

Problem:

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

Code:

<?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);
}


?>
Kai
  • 5,850
  • 13
  • 43
  • 63
Dimas
  • 47
  • 1
  • 9

2 Answers2

4

Remove comma after last column:

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

Also you don't need to alias the same name as column:

$sql = "SELECT 
             `username`,
             `firstname`,
             `lastname`,
             `email`  
         FROM `user` WHERE `id` = {$id}";
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
0

The issue is with the syntax formation for the sql query in $sql, as the error itself tells that the error is near FROM user WHERE id=0, the additional comma , near email in select query throws the sql error.

<?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();

?>
Kishore Sahasranaman
  • 4,013
  • 3
  • 24
  • 50