gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:58:52 25 4
gpt4 key购买 nike

如果我想获得某个品牌的 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'];
}

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

最佳答案

$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

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

关于php - 从数据库值填充数组的最有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3834448/

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