dongnai8013 2012-03-14 15:25
浏览 72
已采纳

将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.

  • 写回答

1条回答 默认 最新

  • dongliao9018 2012-03-14 15: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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部