2015-11-01 28 views
2

我有這個問題的錯誤,我不知道如何解決它。我知道這麼多人有問題像我的問題,但我不能定位。無效的查詢:您的SQL語法有錯誤;語法使用附近

問題:

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


?> 

回答

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}"; 
+2

謝謝你這麼多lad2025 – Dimas

0

的問題是與語法形成了在$sql SQL查詢,因爲錯誤本身告訴錯誤是附近FROM user WHERE id=0,附加comma ,附近emailselect查詢拋出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(); 

?> 
+1

謝謝你的回答,但lad2025幫我已經:) – Dimas

+0

很好聽,你的問題解決了:) –