dongnai8013
dongnai8013
2012-03-14 23:25

将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 dongliao9018 9年前

    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.

    点赞 评论 复制链接分享