1

I'm trying to convert sqlite query into json. I have the following table with two columns name and age. When I print the query the format doesn't seem to be correct. why am I getting an extra key value pair?

<?php
$db = new SQLite3('info.db');

$results = $db->query('SELECT * FROM info');
while ($row = $results->fetchArray()) {

    $jsonArray[] = $row;
}

echo json_encode($jsonArray)
?>

output

[{"0":"billy","name":"billy","1":"20","age":"20"}]

desired output

    [{"name":"billy","age":"20"}]
2
  • 1
    fetchArray grabs both association and numerical array indexes. It defaults to SQLITE3_BOTH, use either SQLITE3_ASSOC or SQLITE3_NUM instead. Commented Nov 13, 2018 at 5:04
  • cloud916 check and try answer given below and let us know if any-one worked for you Commented Nov 13, 2018 at 8:10

4 Answers 4

4

Follow an example:

<?php
    $db = new SQLite3('info.db');
    $results = $db->query('SELECT * FROM info');
    $data = array();
    while ($row = $results->fetchArray(SQLITE3_ASSOC)) {
        array_push($data, $row);
    }
    echo json_encode($data);
?>
Sign up to request clarification or add additional context in comments.

Comments

2

Change query to get only those column which are required:

$results = $db->query('SELECT name,age FROM info'); 
// if you want all column then only use *

And then use SQLITE3_ASSOC

while($row = $results->fetchArray(SQLITE3_ASSOC)){ 

Reference:- SQLite3Result::fetchArray

Parameters

mode

Controls how the next row will be returned to the caller. This value must be one of either SQLITE3_ASSOC, SQLITE3_NUM, or SQLITE3_BOTH.

SQLITE3_ASSOC: returns an array indexed by column name as returned in the corresponding result set

SQLITE3_NUM: returns an array indexed by column number as returned in the corresponding result set, starting at column 0

SQLITE3_BOTH: returns an array indexed by both column name and number as returned in the corresponding result set, starting at column 0

Comments

0

Easier than all that

<?php
  $db = new SQLite3('info.db');
  $result = $db->query('SELECT * FROM info');
  $rows->fetchArray(SQLITE3_ASSOC);
  echo json_encode($rows);
?>

Comments

-1

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

say you can use this if you using pdo

$result = $sth->fetch(PDO::FETCH_OBJ);

$sth is your query

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.