If I wanted to get a list of product_ids with a certain brand. I would do this:
如果我想获得具有特定品牌的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'];
}
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.
有更快更有效的方式吗?看起来如果我只选择1列,应该有更好的方法来选择/插入数组。
1 个解决方案
#1
4
$STH->setFetchMode(PDO::FETCH_COLUMN,0);
$id_list = $STH->fetchAll();
Is it really faster? Local benchmarK:
真的更快吗?当地的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...
..所以,在我的服务器上,至少这个脚本差异更快......
#1
4
$STH->setFetchMode(PDO::FETCH_COLUMN,0);
$id_list = $STH->fetchAll();
Is it really faster? Local benchmarK:
真的更快吗?当地的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...
..所以,在我的服务器上,至少这个脚本差异更快......