Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top