dongnai8013
2012-03-14 23:25
浏览 67
已采纳

将PHP变量添加到SQL语句中。 不工作

I can't get a variable to work in SQL statement. I can get it to work when I replace (username = $user) with (ID = 11) which is another column from database and a specific row (11), but I want to include a specific row matching $user from column 'username', along with other random results with a limit of $sn.

When using var_dump($user) I know that the variable has a value, but can't see why it doesn't work in SQL statement.

$photo=mysql_query("SELECT A. * FROM (
SELECT DISTINCT * FROM profile_images
WHERE approved='N'  
ORDER BY (username = $user) DESC, RAND()      
LIMIT $sn) 
as A ORDER BY RAND()");

Getting error message: 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 '@googlemail.com) DESC, RAND() LIMIT 9) as A ORDER BY RAND()' at line 4

Any help appreciated.

图片转代码服务由CSDN问答提供 功能建议

我无法在SQL语句中使用变量。 当我用(ID = 11)替换(username = $ user)时,我可以让它工作,这是数据库和特定行(11)中的另一列,但我想在列'用户名'中包含一个与$ user匹配的特定行 ',以及其他随机结果,限制为$ sn。

使用var_dump($ user)时我知道变量有一个值,但是看不出它在SQL语句中不起作用的原因。

  $ photo = mysql_query(“SELECT A. * FROM(
SELECT DISTINCT * FROM profile_images 
WHERE approved ='N'
ORDER BY(username = $ user)DESC,RAND()
LIMIT $ sn)  
as ORDER BY RAND()“); 
   
 
 

获取错误消息:SQL语法中有错误; 检查与MySQL服务器版本对应的手册,以便在'@ googlemail.com附近使用正确的语法)DESC,RAND()LIMIT 9)作为第4行的ORDER BY RAND()'

任何帮助表示赞赏。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dongliao9018 2012-03-14 23:28
    最佳回答

    Assuming $sn holds integer value and don't require escaping,

    $photo=mysql_query("SELECT A. * FROM ( 
    SELECT DISTINCT * FROM profile_images 
    WHERE approved='N'   
    ORDER BY (username = '".mysql_real_escape_string($user)."') DESC, RAND()       
    LIMIT $sn)  
    as A ORDER BY RAND()"); 
    

    In general, consider using PDO and bind parameters.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题