0

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

2 Answers 2

2

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.

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

1 Comment

Thank you guys for your hall it works very well ! ;)
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.