且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

意外地通过单个PDO查询达到了PHP内存限制?

更新时间:2023-10-27 21:45:52

在调用查询之前,内存使用量为635384字节.我猜查询为每个记录按块分配.

Memory usage is 635384 bytes before calling query. I'm guessing query allocates in chunks, for each record.

叮叮叮!

当连接到MySQL时,PHP喜欢使用缓冲的查询.不管您使用哪种连接方法,都是如此.使用缓冲查询时,整个结果集将立即获取,而不是在您询问时获取. 通常对性能有好处,因为往返次数较少.

When connecting to MySQL, PHP likes using buffered queries. This is true regardless of what method you're using to connect. When using buffered queries, the entire resultset is fetched immediately instead of being fetched when you ask. This is usually good for performance, as there are fewer round-trips.

但是,就像PHP中的所有内容一样,有一个陷阱.如缓冲页面上所述:

But like everything in PHP, there's a gotcha. As noted on the buffering page:

使用libmysql作为库时,除非将数据提取到PHP变量中,否则PHP的内存限制不会计算结果集使用的内存.使用mysqlnd时,所占内存将包括完整的结果集.

When using libmysql as library PHP's memory limit won't count the memory used for result sets unless the data is fetched into PHP variables. With mysqlnd the memory accounted for will include the full result set.

您正在使用PHP 5.3,这意味着您很有可能正在使用mysqlnd.

You're using PHP 5.3, which means that there's a good chance that you're using mysqlnd.

您将要在此处关闭缓冲的查询.在与MySQL的每个PHP接口中,操作都不同:

You'll want to turn off buffered queries here. It's done differently in every PHP interface to MySQL:

  • 对于PDO,您需要将PDO::MYSQL_ATTR_USE_BUFFERED_QUERY属性设置为false.
  • 对于mysqli,您需要将MYSQLI_USE_RESULT常量传递给 query 方法. /li>
  • 对于mysql,您需要调用mysql_unbuffered_query而不是mysql_query.
  • For PDO, you'll need to set the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute to false.
  • For mysqli, you need to pass the MYSQLI_USE_RESULT constant to the query method.
  • For mysql, you need to call mysql_unbuffered_query instead of mysql_query.

完整的详细信息和示例在页面上.

Full details and examples are on the page.

必须必须正确关闭语句句柄并释放结果集,然后再发出另一个查询:

You must properly close the statement handle and free the result set before issuing another query:

  • 在PDO中,这意味着在语句句柄上调用 closeCursor .
  • 在mysqli中,这意味着在语句句柄或上调用 free_result 关于结果句柄的href ="http://php.net/mysqli-result.free" rel ="noreferrer"> free ,具体取决于您使用的是什么.
  • 在mysql中,这意味着调用 mysql_free_result

否则将导致错误.