Caesius
Caesius

Reputation: 267

PHP JSON array from SQLite3

I'm trying convert data from a SQLite3 db to a JSON array by using PHP. I'm getting close, but I can't seem to get it right.

This is the error I'm getting: PHP Warning: PDOStatement::fetchAll() expects parameter 1 to be long, object given in...

Thanks!

<?php
$db = new PDO('sqlite:example.db');

$result = $db->query('SELECT * FROM test');

$json = array();

$result->setFetchMode(PDO::FETCH_ASSOC);

while ($data = $result->fetchall($result)){

$x = $data['Time'];
$y = $data['Temperature'];

$json[] = array( (int($x)), (int($y)) );
}
?>

Upvotes: 2

Views: 7508

Answers (3)

Caesius
Caesius

Reputation: 267

Got it working now. Thanks for your help!

<?php

$db = new PDO('sqlite:example.db');

$result = $db->query('SELECT * FROM test');

$datapie = array();

$result->setFetchMode(PDO::FETCH_ASSOC);

while ($row = $result->fetch()) {

extract($row);

$datapie[] = array(floatval($Temperature), $Time);
}

$data = json_encode($datapie);

?>

Upvotes: 4

Barmar
Barmar

Reputation: 780919

Change:

$result->fetchall($result)

to:

$result->fetch()

You had two problems: the argument to fetchAll() should be a fetch mode, not a result. And fetchAll() returns all the rows, not one row at a time. If you're calling in a loop you use fetch().

Upvotes: 1

Ivan Yonkov
Ivan Yonkov

Reputation: 7034

PDO's fetchAll function, doesn't expect the query itself as a param.

Check it's manual here - you can leave it blank, or set the fetch mode:

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

Upvotes: 0

Related Questions