JSON value encoded twice : how to use fetch_assoc()?

隐身守侯 提交于 2019-12-10 22:33:25

问题


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.


回答1:


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

You should try:

$req->fetch(PDO::FETCH_ASSOC)



回答2:


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.



来源:https://stackoverflow.com/questions/16498975/json-value-encoded-twice-how-to-use-fetch-assoc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!