gpt4 book ai didi

php - 为什么要检查 mysql_real_escape_string() 的返回值

转载 作者:可可西里 更新时间:2023-11-01 08:52:49 24 4
gpt4 key购买 nike

在我读过的每一篇博客/文章/问答中,都没有人建议检查 mysql_real_escape_string() 返回的值。

在我看来,这个检查对于确保数据一致性非常重要,因为如果这个函数失败,插入到数据库中的值将是一个误报: bool 值 FALSE 类型转换为字符串,结果为空字符串,不是您所期望的。

根据文档:

Returns the escaped string, or FALSE on error. 

A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn't defined, the last MySQL connection is used.

如果您在日志中查看发生了什么,警告是好的,但不会阻止它发生。

我知道很少有更改会失败,但如果至少有一项更改应该是您的应用程序所期望的。

如果出现以下情况,此函数将失败:

  • 开发者在调用这个函数之前没有连接到数据库
  • 调用此函数前数据库连接失败
  • 服务器(mysql客户端所在)内存不足,无法复制转义字符串
  • ...

这是一个“正常”用法的例子:

$db = mysql_connect() or die('Cannot connect to database');
$value = mysql_real_escape_string($_POST['value'], $db);
mysql_query('insert into tablex (value) values ("'.$value.'")', $db) or die('Cannot insert data in database');

我正在使用这样的东西(在 mysql 的 OO 包装器中):

class mywrapper{
// ... [code ...]

// $this->db is the mysql link identifier
public function escape($string)
{
if(mysql_real_escape_string($string, $this->db) === false)
{
throw new Exception('Some message');
}
}
} // end class

// I'm calling it as
// $myWrapper->insert('insert into tablex (value) values ("'.($myWrapper->escape($value)).'")');

这将引发一个异常,该异常将被异常处理程序捕获,最重要的是我防止在数据库中插入误报值,确保数据一致性。

我错过了什么?我是在谨慎行事,还是我有点偏执? :)

最佳答案

从某种意义上说,你错过了一些东西,因为它是 no longer recommended to use the mysql_函数族。而是使用 mysqliPDO .这两者都提供参数化查询,这些查询将自动为您转义您的输入数据。

关于php - 为什么要检查 mysql_real_escape_string() 的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10315286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com