简体   繁体   中英

Most efficient way to populate array from database values?

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.

$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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM