2

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)) );
}
?>
3
  • Try removing the line with $result->setFetchMode(PDO::FETCH_ASSOC), and do this on the while line: while ($data = $result->fetchAll(PDO::FETCH_ASSOC)) Commented May 18, 2013 at 9:43
  • You don't call fetchAll in a loop, it returns all the results at once as a 2-dimensional array. Commented May 18, 2013 at 9:43
  • Good point, the call should be $result->fetch(), not $result->fetchAll(). Alternatively, you could call $data = $result->fetchAll() first, then turn the while loop into a foreach loop. Commented May 18, 2013 at 9:46

3 Answers 3

4

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);

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

Comments

1

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().

Comments

0

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

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.