3

I'm trying to return all records from my database where the userID is equal to the logged in user.

I have the following only for some reason its not returning anything, can anybody see any obvious errors?

<?php 
$interestsquery  = "SELECT * 
                      FROM user_interests 
                     WHERE user_id = $usersClass->userID()";
$result = mysql_query($interestsquery);

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo "{$row['interest']}";
} 
?>
1
  • 1
    Obvious that your PHP is not catching MySQL errors so you could debug... Commented Jul 3, 2011 at 20:42

4 Answers 4

5

Unfortunately, you can't call functions and have them parsed that way. You'll either need to concatenate manually, or set a variable and parse that.

Try this:

"SELECT * FROM user_interests WHERE user_id = " . $usersClass->userID();

Or this:

$uid = $usersClass->userID();
"SELECT * FROM user_interests WHERE user_id = $uid";
Sign up to request clarification or add additional context in comments.

2 Comments

or "SELECT * FROM user_interests WHERE user_id = {$usersClass->userID()}"; but still he should be using the quoting function
yea... I don't like calling functions inside strings (Yes, I know it's different, but... somehow...)
4

The method call is a complex enough expression that you should probably enclose it in expression interpolation delimiters:

$interestsquery  = "SELECT * FROM user_interests WHERE user_id = {$usersClass->userID()}"

But I also recommend abandoning the primitive PHP/mysql extension and moving to PDO, so you can use query parameters. Then you don't have to hassle with string interpolation at all, and you gain better habits for writing code that resists SQL injection vulnerabilities.

$interestsquery  = "SELECT * FROM user_interests WHERE user_id = ?"
$stmt = $pdo->prepare($interestsquery);
$result = $stmt->execute(array( $usersClass->userID() ));

2 Comments

Thanks Bill, Im still learning PHP so im very new to a lot of the things Im seeing here, would it be wise to read up on PDO now or wait until I understand the entire fundamentals of PHP first?
PDO is really not that hard. I recommend using PDO and forgetting that the plain mysql extension exists. I wish that they'd deprecate the mysql extension.
2

try this:

$interestsquery  = "SELECT * FROM user_interests WHERE user_id =".$usersClass->userID();

Comments

2

Try

$interestsquery  = "SELECT * FROM user_interests 
                    WHERE user_id = ".$usersClass->userID();

And make sure $usersClass->userID() returns a valid integer user id.

Comments

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.