简体   繁体   中英

PHP mySQL query for updating row in table using variables

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");    
}

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");

//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");

完成后,您必须对字符串使用单引号,但不需要整数

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

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");

$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");

 $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"); 

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM