Search code examples
phpmysqldrupaldrupal-7

Drupal / MySQL fetchAllAssoc(); resulting in exception


I have an external database that I am trying to access from within a Drupal page, I have successfully queried the database and output data to the page using fetchAssoc(), however this only returns the first row in the database. I would like to return all rows into an array for processing, so I'm attempting to use fetchAllAssoc(), this however results in an exception. The database has the following SQL fields:

id, model, manufacturer, url, date_modified

My test code is as follows:

<?php
db_set_active('product_db');
$query = db_select('product', 'p')->fields('p');
$sqlresults = $query->execute()->fetchAllAssoc('id');
foreach($sqlresults as $sqlresult)
{
printf($sqlresult);
}
db_set_active();
?>

I'm thinking that it is the key field 'id' that I am specifying with fetchAllAssoc() that is the problem, as fetchAssoc() prints values correctly. All documentation I have found seems to say that you pass a database field as the key but I have also passed a numeric value with no success.

Many thanks in advance for any advice, I'm sure I'm just missing something stupid.


Solution

  • I think it should work in this way, but within the foreach you want to print the $sqlresult variable as a string, but it is an object (it causes the error).
    printf function needs a string as the first parameter, see:
    http://php.net/manual/en/function.printf.php

    Use for instance var_dump instead:

    var_dump($sqlresult);