在PHP中清理目标为数据库的用户输入

在PHP中清理目标为数据库的用户输入,php,sql-injection,code-injection,sanitization,sanitize,Php,Sql Injection,Code Injection,Sanitization,Sanitize,我有以下代码: $query = "select id from votes where username = '$user' and article_id = $this->id"; 我尝试了以下代码对其进行清理: $query = sprintf("select id from votes where username = '$user' and article_id = $this->id", mysql_real_escape_string($user),

我有以下代码:

$query = "select id from votes where username = '$user' and article_id  = $this->id";
我尝试了以下代码对其进行清理:

$query = sprintf("select id from votes where username = '$user' and article_id = $this->id", 
    mysql_real_escape_string($user), 
    mysql_real_escape_string($password));
但是我在mysql\u real\u转义行中得到了这个错误:

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
我在这里得到了用户名,我不知道它是否足够安全:

function getUsername(){ return $this->username; }

Thx

在使用mysql\u real\u escape\u字符串之前,您需要一个mysql连接。

不确定这是否是导致问题的原因,但我相信sprintf语句中的变量不应该是“$user”和“$this->id”,而应该是“%s”


我建议使用一个成熟的DB抽象层,比如(有很多)。实现您自己的自制解决方案并不是我推荐用于生产系统的东西。

您需要一个连接来使用mysql\u real\u escape\u string(),因为它使用服务器的编码类型来帮助santitize

sprintf()也应该是这样的

$query = sprintf("SELECT id FROM votes WHERE username = '%s' and article_id = %d", 
    mysql_real_escape_string($user), 
    mysql_real_escape_string($password));
我建议使用for this,而不是
sprintf

警告:mysql\u real\u escape\u string() [function.mysql real转义字符串]: 用户的访问被拒绝 'mexautos'@'localhost'(使用 密码:否)

警告:mysql\u real\u escape\u string() [function.mysql实转义字符串]:A 无法创建到服务器的链接 确立

你查过链接了吗?它是活动的吗?您需要先连接,然后才能使用 你忘了设置密码吗

尝试:

(如果没有密码,请键入Enter)

另外,请检查您的函数,您需要使用%s绑定变量

$a = 'Foo';
$b = 'Bar';
$foo = sprintf('Foo Bar %s %s', $a, $b);

就像另一个所说的,不是“$user”,而是“%s”,您需要一个打开的连接

@托马拉克
sprintf更快——这就是为什么要使用它的原因——它是一个本机C函数。

更不用说他试图用一个名为$password的变量替换文章id。为什么要使用sprintf()——PHP在字符串中有变量插值。OTOH,使用sprintf()构建的SQL语句与插值语句一样不安全。。。这两种方法都应该避免使用。@Tomalak-我知道,但他只是强调了代码中的一个错误,没有提出更好的方法。在我的代码中,我不确定id是否一定是整数,所以我只使用字符串格式。如果mysql接口支持它们,这是个好主意。他需要切换到mysqli或PDO来使用预先准备好的语句。如果他使用的是php5或更高版本,那么mysqli就包括在内。尝试通过控制台连接是以原始方式检查权限的一种方式!sprintf比什么更快?当与数据库交互时,这不是一个特别好的理由…sprintf比构建PHP字符串插值更快,它与数据库主题无关,但与Tomalak的评论有关。我确实有连接,我的意思是,在插入这些行之前,站点工作并连接到数据库。Thx.这不是错误所说的!尝试使用链接标识符作为mysql\u real\u escape\u字符串的第二个参数,看看这是否有帮助。
$a = 'Foo';
$b = 'Bar';
$foo = sprintf('Foo Bar %s %s', $a, $b);