在PHP中清理发往数据库的用户输入

jcs*_*lzr 0 php sanitization sql-injection code-injection sanitize

我有这个代码:

$query = "select id from votes where username = '$user' and article_id  = $this->id";
Run Code Online (Sandbox Code Playgroud)

我尝试使用此代码来清理它:

$query = sprintf("select id from votes where username = '$user' and article_id = $this->id", 
    mysql_real_escape_string($user), 
    mysql_real_escape_string($password));
Run Code Online (Sandbox Code Playgroud)

但我得到mysql_real_escape行的这个错误:

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'mexautos'@'localhost' (using password: NO) in /home/mexautos/public_html/kiubbo/data/article.php on line 145 Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home/mexautos/public_html/kiubbo/data/article.php on line 145 Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'mexautos'@'localhost' (using password: NO) in /home/mexautos/public_html/kiubbo/data/article.php on line 146 Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home/mexautos/public_html/kiubbo/data/article.php on line 146
Run Code Online (Sandbox Code Playgroud)

我在这里得到了用户名,我不知道它是否足够安全:

function getUsername(){ return $this->username; }
Run Code Online (Sandbox Code Playgroud)

谢谢

whi*_*dan 8

在使用mysql_real_escape_string之前,您需要一个mysql连接.


Joh*_*sch 7

我建议使用预备语句代替sprintf