PHP mySQL查询使用变量更新表中的行

PHP mySQL查询使用变量更新表中的行

问题描述:

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

我的PHP文件包含以下函数。 当我将审核列设置为'$ review' code>并将 IdUser code>设置为2时,它可以正常工作。但我需要将 IdUser code>设置为 变量 $ user code>。 将 IdUser code>设置为变量而不是常量的正确语法是什么? (最好以避免SQL注入攻击的方式)。 p>

  function addRatings2($ review,$ user){
 //尝试使用给定的UserID 
 $ result = query在“ratings”表中插入新行 (“UPDATE rating SET review ='$ review'WHERE IdUser = 2 order by dateTime desc limit 1”);  
} 
  code>  pre> 
  div>

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

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

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

}