$file_db = new PDO('sqlite:test.db');
if($file_db){
$result = $file_db->query('SELECT id FROM sample');
$encodable = array();
while($obj = $result->fetch())
{
$encodable[] = $obj;
}
$encoded = json_encode($encodable);
echo $encoded;
}else{
die("unable to conenct to db");
}
I just want to output {"id":"1"} but it also gives me "0":"1". Does anyone know why?
Result:
[{"id":"1","0":"1"},{"id":"2","0":"2"},{"id":"3","0":"3"},{"id":"4","0":"4"},{"id":"5","0":"5"},{"id":"6","0":"6"},{"id":"7","0":"7"},{"id":"8","0":"8"},{"id":"9","0":"9"},{"id":"10","0":"10"},{"id":"11","0":"11"},{"id":"12","0":"12"},{"id":"13","0":"13"},{"id":"14","0":"14"}]
Is because of the way you are fetching the data with PDO.
PDOStatement::fetchenables you to choose if you want an associative array, an indexed array and more. The default is to have both. Change it to that to have the behaviour you are expecting:while($obj = $result->fetch(PDO::FETCH_ASSOC))