0

My PHP file contains the following function. It works when I set the review column to '$review' and the IdUser to 2. But I need to have the IdUser set to the variable $user. What is the correct syntax to set IdUser to the variable instead of a constant? (preferably in a way that avoids SQL injection attacks).

function addRatings2($review, $user) {  
    //try to insert a new row in the "ratings" table with the given UserID
    $result = query("UPDATE ratings SET review ='$review' WHERE IdUser = 2 order by dateTime desc limit 1");    
}
2
  • Is $user a string or an integer variable? Strings must be single-quoted just as you have '$review' and escaped via the proper method for whatever database API you are calling with query() (for example mysql_real_escape_string()). Commented May 23, 2013 at 3:00
  • $user is an integer value Commented May 23, 2013 at 3:09

4 Answers 4

1

Hi the right syntax is to use

{$var} wherever you want the current value of var to appear, so in your case it would be

$result = query("UPDATE ratings SET review ='{$review}' WHERE IdUser = {$user}
order by dateTime desc limit 1");
Sign up to request clarification or add additional context in comments.

4 Comments

oh and to avoid the SQL injection you must use the stripslashes and mysql_real_escape_string functions
The {$var} isnt working. However if I use single quotes '$var' it works for the review variable but not for the user variable (UserId='$user')
ooops nevermind I wasnt passing the userID as session in my PHP. Your syntax os exactly correct!!!
It should but the other way would be to concatenate the var to the string like this $result = query("UPDATE ratings SET review ='$review' WHERE IdUser = " . $user . " order by dateTime desc limit 1"); The dot (.) character is the concatenation operator in php
1

//anti-injection

$user = (int)$user;

$review = mysql_real_escape_string($result); //mysqli_real_escape_string will be better

$result = query("UPDATE ratings SET review ='$review' WHERE IdUser = $user order by dateTime desc limit 1");

Comments

1

You must use single quotes for a string as you have done, but you don't need to for an integer

query("UPDATE ratings SET review ='$review' WHERE IdUser = $user order by dateTime desc limit 1");

Comments

0

Try this one. function addRatings2($review, $user) {

$review = mysql_real_escape_string($review);

$user = (int)$user

$result = query("UPDATE ratings SET review ='$review' WHERE IdUser = $user order by        dateTime desc limit 1");    

}

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.