سؤال

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":"johntest@gmail.com","4":"johntest@gmail.com","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

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top