从数据库值填充数组的最有效方法?

发布于 2024-09-26 06:33:35 字数 407 浏览 4 评论 0原文

如果我想获取某个品牌的product_ids 列表。我会这样做:

$id_list = array();
$qry = 'SELECT product_id FROM products WHERE product_brand = :brand';
$STH = $this->pdo->prepare($qry);
$STH->execute(array("brand" => $brand));
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch())
{
    $id_list[] = $row['product_id'];
}

有没有更快更有效的方法?似乎如果我只选择一列,应该有更好的方法来选择/插入到数组中。

If I wanted to get a list of product_ids with a certain brand. I would do this:

$id_list = array();
$qry = 'SELECT product_id FROM products WHERE product_brand = :brand';
$STH = $this->pdo->prepare($qry);
$STH->execute(array("brand" => $brand));
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch())
{
    $id_list[] = $row['product_id'];
}

Is there a faster more efficient way? It seems like if I am only selecting 1 column there should be a better approach to selecting/inserting that into an array.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

勿忘初心 2024-10-03 06:33:35
$STH->setFetchMode(PDO::FETCH_COLUMN,0);
$id_list = $STH->fetchAll();

真的更快吗?本地基准:

$ cat 1.php 
<?php
$d = new PDO('mysql:localhost');
$qry = 'SELECT SQL_NO_CACHE bar FROM test.foo'; //for completeness sake: foo has 400 rows
$stmt = $d->query($qry);
$stmt->setFetchMode(PDO::FETCH_COLUMN,0);
$check = $stmt->fetchAll();
?>
$ cat 2.php 
<?php
$d = new PDO('mysql:localhost');
$qry = 'SELECT SQL_NO_CACHE bar FROM test.foo'; //for completeness sake: foo has 400 rows
$stmt = $d->query($qry);
$check = array();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row = $stmt->fetch()){
        $check[] = $row['bar'];
}
?>
$ time (for i in {1..100}; do php 1.php; done;)

real    0m4.507s
user    0m2.392s
sys     0m1.288s
$ time (for i in {1..100}; do php 2.php; done;)

real    0m6.830s
user    0m3.352s
sys     0m2.328s

..所以,至少这个脚本差异在我的服务器上更快......

$STH->setFetchMode(PDO::FETCH_COLUMN,0);
$id_list = $STH->fetchAll();

Is it really faster? Local benchmarK:

$ cat 1.php 
<?php
$d = new PDO('mysql:localhost');
$qry = 'SELECT SQL_NO_CACHE bar FROM test.foo'; //for completeness sake: foo has 400 rows
$stmt = $d->query($qry);
$stmt->setFetchMode(PDO::FETCH_COLUMN,0);
$check = $stmt->fetchAll();
?>
$ cat 2.php 
<?php
$d = new PDO('mysql:localhost');
$qry = 'SELECT SQL_NO_CACHE bar FROM test.foo'; //for completeness sake: foo has 400 rows
$stmt = $d->query($qry);
$check = array();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row = $stmt->fetch()){
        $check[] = $row['bar'];
}
?>
$ time (for i in {1..100}; do php 1.php; done;)

real    0m4.507s
user    0m2.392s
sys     0m1.288s
$ time (for i in {1..100}; do php 2.php; done;)

real    0m6.830s
user    0m3.352s
sys     0m2.328s

.. so, at least this script difference, on my server, is faster...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文