Reputation: 2500
Problem related to php
& sql3lite
. I want to get multi-array from SQLite3Result
. I found function exactly what I need http://php.net/manual/en/sqlite3result.fetcharray.php
I try (php code):
$results = $db->query('SELECT * FROM table');
$multiarray = $results->fetchAll(SQLITE_ASSOC);
But got:
Fatal error: Call to undefined method SQLite3Result::fetchAll() in
Where is the problem? Seems this function was removed from php5
? Any alternatives to get multiarray
? thanks
Upvotes: 4
Views: 12356
Reputation: 831
Create a separate function to get all as
function sqliteFetchAll(\SQLite3Result $results, $mode = SQLITE3_ASSOC): array
{
$multiArray = [];
while($result = $results->fetchArray($mode)) {
$multiArray[] = $result;
}
return $multiArray;
}
Upvotes: 2
Reputation: 81
Here's one way to read all the rows into an array:
$db = new \SQLite3("database.dat", SQLITE3_OPEN_READWRITE); //open DB
$result = $db->query("SELECT * FROM main"); //SQL query
$resultArray = $result->fetchArray(SQLITE3_ASSOC); //temporary variable to store each row
$multiArray = array(); //array to store all rows
while($resultArray !== false){
array_push($multiArray, $resultArray); //insert all rows to $multiArray
$resultArray = $result->fetchArray(SQLITE3_ASSOC); //read next row
}
unset($resultArray); //unset temporary variable
//now all rows are now in $multiArray
var_dump($multiArray);
When no more rows are to be read, $result->fetchArray(SQLITE3_ASSOC);
returns false
. So we simply run a loop until that happens, and push each array into a multi-dimensional array $multiArray
.
(Tested on PHP 7+)
Upvotes: -1
Reputation: 41
Try
$multiarray = $results->fetchArray();
instead of
$multiarray = $results->fetchAll(SQLITE_ASSOC);
Upvotes: -2
Reputation: 5270
This is the easiest way to fetch data from database in SQLite3
in php
$db = new SQLite3('mysqlitedb.db');
$results = $db->query('SELECT bar FROM foo');
while ($row = $results->fetchArray()) {
var_dump($row);
}
Upvotes: 2
Reputation: 9432
As stated in the comments you can extend something like:
<?php
$x = new SQLite3_1('xx.db');
//see: http://www.icosaedro.it/phplint/phplint2/doc/modules/sqlite3.html
class SQLite3_1 extends SQLite3
{
public function __construct($filename,int $flags = 6, string $encryption_key = "")
{
parent::__construct($filename,$flags,$encryption_key);
}
public function fetchAll()
{
//own implementation with a FOR (is faster than a foreach)
}
public function numberResults()
{
//helpfull
}
}
?>
It is not elegant as you stated but when migrating to different servers (and different versions of PHP) you won't have headaches this way
Upvotes: 0