创建PDO迭代器 [英] Creating PDO Iterator

查看:89
本文介绍了创建PDO迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在流动文章创建数据库迭代器.我有类似的表格和记录.但是,当我执行我得到空白页.我认为是$data = new DbRowIterator($stmt);上的问题,它没有返回正确的迭代器来运行FilterIterator类中的accept方法.我正在使用laravel

I'm flowing this article to create Database Iterator. I've similar tables and records. But when I executing I'm getting blank page. I think issue on $data = new DbRowIterator($stmt);, It's not returning proper iterator to run accept method in FilterIterator class. I'm using laravel

推荐答案

本文是恶作剧.它声称所提供的技术可以加快PDO的数据库调用速度,但实际上会使它们变慢显着地.

This article is a hoax. It claims that offered technique would speed up database calls with PDO, but in fact it slows them down significantly.

它所基于的前提也是错误的. PDOStatement已经可以遍历了,您不需要任何技巧就可以使用foreach遍历PDOStatement.

Premises on which it is grounded are also wrong. PDOStatement is already traversable, you don't need no tricks to iterate over PDOStatement using foreach.

基准测试部分(经常发生)是一个明显的骗局.那个家伙正在比较fetchAll(),这显然会消耗大量的时间/内存,而一次只获取一行.而且即使这样,他的时机也比采用正确的解决方案要糟糕得多.

The benchmarking section (as it often happens) is a blatant swindle. The guy is comparing fetchAll(), which obviously consumes a lot of time/memory, with fetching a single row at a time. And even this way his timing is much worse than with a proper solution.

撰写本文的人不知道PDO,而且-更糟糕的是-不知道SQL.

The guy who wrote this article knows no PDO and - worse yet - no SQL.

他发明的所有已经存在的在PDO和SQL中:

Everything he invented already exists in PDO and SQL:

  1. PDOStatement已经可以遍历.无需重新发明轮子.
  2. 最重要的部分:过滤必须在SQL中完成,而不是在PHP中完成.这是一条教科书规则.如果在250000条记录中只需要63992,则应该仅选择63992.而且,如果您要求数据库为您选择记录,它将是无与伦比的.
  1. PDOStatement is already traversable. No need to reinvent the wheel.
  2. The most important part: filtering has to be done in SQL, not in PHP. That's a textbook rule. If you need only 63992 out of 250000 records, you should select only 63992 in the first place. And if you ask a database to select the records for you, it will be incomparable faster.

因此,要获得这个人所做的一切努力,您只需使用PDO几行即可

So, to get everything this guy wrote with such effort, you need only few lines with PDO

$period = date_create("last_week")->format('Y-m-d 00:00:00');
$sql = 'SELECT * FROM `gen_contact` WHERE contact_modified  > ? ORDER BY `contact_modified` DESC';
$stmt = $pdo->prepare($sql);
$stmt->execute([$period]);
foreach ($stmt as $row) {
    echo sprintf(
        '%s (%s)| modified %s',
        $row->contact_name,
        $row->contact_email,
        $row->contact_modified
    ) . PHP_EOL;
}

并且此代码将在数据库级别进行过滤,而不是获取整个表,然后在PHP端进行过滤,因此速度快了.

And this code will be a multitude times faster as it does the filtering on the database level, instead of fetching the whole table and then filtering on PHP side.

从发生错误时开始,只需将PDO设置为异常模式,并注意常规的PHP错误

As of the error you get, just set PDO in exception mode and watch for the regular PHP errors.

这篇关于创建PDO迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆