0

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 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Have cast $sn to integer using intval. Not quite sure what PDO and bind parameters are but will look them up. Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.