2012-07-07 84 views
1

這裏是PHPSQL語法錯誤。看起來像我錯過了什麼

$query = sprintf("SELECT SUM(value) AS totalvalue 
       FROM (
       SELECT * 
       FROM answers 
       WHERE user_id='%s' 
       AND test_id ='%s' 
       ORDER BY answers.id DESC 
       LIMIT '%s' 
       ) 
       AS subquery", 
       $user_id, 
       mysql_real_escape_string($test_id), 
       $num_of_q); 

這裏結合我的SQL代碼的錯誤:

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 ''40') AS subquery' at line 8

有什麼問題嗎?從限值

+0

只是旁註:因爲你只需要'值'列,不要在子查詢中使用'select *'。在那裏使用'select value',爲引擎提供更多優化查詢的可能性 – 2012-07-07 08:24:08

回答

3

刪除'',並使用數字時使用%d

$query = sprintf("SELECT SUM(value) AS totalvalue 
      FROM (
      SELECT * 
      FROM answers 
      WHERE user_id='%s' 
      AND test_id ='%s' 
      ORDER BY answers.id DESC 
      LIMIT %d 
      ) 
      AS subquery", 
      $user_id, 
      mysql_real_escape_string($test_id), 
      $num_of_q); 
1

您不需要引號LIMITLIMIT需要後面的數字,而您提供了一個字符串。

將其更改爲:

LIMIT %d 

我建議你做同樣與test_iduser_idWHERE條款,如果他們是類型INT

2

我想你掃描限值爲字符串。閱讀它作爲int值。這將解決我認爲的問題

相關問題