Reputation: 71
I would like to create a json from my database's datas and the json output is like this:
`[{"id":"1","0":"1","nom":"test","1":"test","prenom":"john","2":"john","societe":"","3":"","mail":"[email protected]","4":"[email protected]","type":"creatif","5":"creatif","url":"johntest","6":"johntest"}]`
My php code to doing so is :
$stock = array();
$sql = $bdd->prepare("SELECT * FROM user");
if ($sql->execute())
{
while ($row = $sql->fetch())
$stock[] = $row;
}
print json_encode($stock);
My problem here is that everything is doubled, I have a first data with the good property like "nom":"test"
and then I have a thing out of nowhere "1":"test"
.
How can I get rid of this second thing?
Thank you for your help
Upvotes: 0
Views: 96
Reputation: 64526
Use PDO::FETCH_ASSOC
in the fetch()
call:
while ($row = $sql->fetch(PDO::FETCH_ASSOC))
PDO defaults to PDO::FETCH_BOTH
which returns both the associative array and the numerical keyed array.
Upvotes: 2
Reputation: 26421
Instead of $sql->fetch()
pass FETCH_ASSOC because default it will use PDO::FETCH_BOTH
,
$sql->fetch(PDO::FETCH_ASSOC);
Read PDOStatement::fetch for more details.
Upvotes: 2