views:

45

answers:

1

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.

+4  A: 
$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...

Wrikken
+1 Awesome, thanks!.. I knew there had to be something... Question tho, is this actually faster or just require less typing?
John Isaacks
Hmm, less arrays created, I'd think it's negligible, but I'll have a benchmark in a few minutes.
Wrikken
oh no. Wrikken and his trained zillion iterations tests again.
Col. Shrapnel
Zillion? As if my computer didn't have anything better to do. And AFAIK this is only my second I posted on SO. Feel free to suffer horrible despair because the actual benchmarking, or gloat mercilessly because someone has yet again taken the bait, dear Shrappy.
Wrikken
Wrikken
Don't bother to explain. I know it already. The only thing you're interested in, is reputation points. Don't worry, you'll get enough.
Col. Shrapnel
Dear Rusty Landmine, your arguments don't hold up, your research skills are sorely lacking, and overall the only thing I'm really interested in while visiting this site is of course dodging the possibility of doing some actual real work, just like the rest. Your limited worldview and experience is elas no fault of mine, and your bitterness about actual in the field practices has jaded your appreciation for nuggets of knowledge that don't necessarily encompass a full project. I don't blame you for it, I'll see you there in about 3 short years I believe.
Wrikken