2

The following code returns the value twice, once encoded in JSON :

<?php
    $req = $bdd->prepare('SELECT Date, Open, Close FROM quotes WHERE Symbol = ? AND Date > ? AND Date < ?');
    $req->execute(array($_GET['id'], $_GET['datemin'], $_GET['datemax']));

    $test=array();
    while ($donnees = $req->fetch())
    {
        $test[] = $donnees;
    }

    echo json_encode($test);
?>

[{"Date":"2012-02-29","0":"2012-02-29","Open":"88.14","1":"88.14","Close":"87.60","2":"87.60"},{"Date":"2012-02-28","0":"2012-02-28","Open":"87.83","1":"87.83","Close":"87.77","2":"87.77"},{"Date":"2012-02-27","0":"2012-02-27","Open":"87.41","1":"87.41","Close":"88.07","2":"88.07"}]

I read on some post I have to use fetch_assoc() instead of fetch_array().

But the following code returns nothing : while ($donnees = $req->fetch_assoc()). Nor does this one : while ($donnees = $req->fetch_array()).
I don't get what's wrong.

Community
  • 1
  • 1
pihug12
  • 317
  • 3
  • 14

2 Answers2

2

See manual.
http://www.php.net/manual/en/pdostatement.fetch.php

You should try:

$req->fetch(PDO::FETCH_ASSOC)
mpyw
  • 5,526
  • 4
  • 30
  • 36
1

Well I don't know what req is, but my guess is that it's a PDOStatement object, which only has fetch and fetchAll methods (no fetch_assoc or fetch_array).

You can change PDO's fetch style with the first argument to fetch. It defaults to PDO::FETCH_BOTH (which is like mysql_fetch_array). You can set it to PDO::FETCH_ASSOC, which is like mysql_fetch_assoc if you like.

$req->fetch(PDO::FETCH_ASSOC);
//global setting
$bdd->setFetchMode(PDO::FETCH_ASSOC);

If it's not a PDOStatement, then whatever it is doesn't have fetch_assoc or fetch_array methods. You'll have to look up how to change the fetch mode for whatever it is.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405