0

I have a question about PDO in PHP:

I'm trying to fetch a column from my mysql database, indexed by the id of each row... Now php.net has an example on how to do it: http://www.php.net/manual/en/pdostatement.fetchall.php (example #3)

    <?php
$insert = $dbh->prepare("INSERT INTO fruit(name, colour) VALUES (?, ?)");
$insert->execute(array('apple', 'green'));
$insert->execute(array('pear', 'yellow'));

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Group values by the first column */
var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));
?>

But this doesn't seem to work for me... All i get is:

array {

   [id1] => null;
   [id2] => null;
   [id3] => null;
   ...

}

Even when i copy the exact same code, and only edit the table name etc. Does anyone know what can cause this problem?

6
  • What do $insert->execute(...) statements return? Commented Dec 20, 2013 at 14:08
  • Well it's part of the example on php.net but doesn't really matter actually, I just copied the whole example. Commented Dec 20, 2013 at 14:12
  • Ah if you mean there could be something wrong in my database, this is not the case (: Commented Dec 20, 2013 at 14:13
  • Does echo $sth->errorCode(); produce anything? Commented Dec 20, 2013 at 14:37
  • No, not really, but i'll just leave it at that and select the answer below as a good answer Commented Dec 20, 2013 at 23:10

1 Answer 1

0

As you can see from the output in the example you linked to, it doesn't work the way you expect.

So, just loop over result using while fetch, storing resul in array manually and set whatever index you like.

Sign up to request clarification or add additional context in comments.

1 Comment

Well actually I wanted something like that... I would only have one item in the array where colors are stored in the example, but that's easier to fix than the loop... But yeah I'll probably just loop...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.