Daniel
Daniel

Reputation: 3077

PHP SQLite fetchAll returning empty array

I created this php script which queries a sqlite database as so:

$r = $db->prepare("SELECT * FROM logs WHERE ip=?;");
$r->bindValue(1, $ip, PDO::PARAM_STR);
$r->execute();

if($r->fetchColumn() >= 1) {
   echo "contains columns.. <br />";
$result = $r->fetchAll();
    foreach ($result as $log) {
        echo "in loop";
        $log_ip = $log['ip'];
        $log_userAgent = $log['userAgent'];
        $log_hits = $log['hits'];

        $log_hits = $log_hits++;

        echo "hits " . $log_hits;

        $hitUp = $db->prepare("UPDATE logs SET hits = ? WHERE ip = ?;");
        $hitUp->bindValue(1, $log_hits, PDO::PARAM_INT);
        $hitUp->bindValue(2, $ip, PDO::PARAM_STR);
        $hitUp->execute();
}

However, $r->fetchAll(); is returning an empty array.

I am 100% sure that the row exists and $ip is 127.0.0.1:

sqlite> select * from logs;
1|127.0.0.1|1|Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.54.16 (KHTML, like Gecko) Version/5.1.4 Safari/534.54.16

Any help is greatly appreciated

Upvotes: 0

Views: 3438

Answers (1)

user610650
user610650

Reputation:

You probably need to remove the if($r->fetchColumn() >= 1) as it probably consumes your single result:

Returns a single column from the next row of a result set or FALSE if there are no more rows.

Also, you shouldn't doubt that you have at least a column, you should instead verify if $result is empty.

Perhaps try that by running something like this:

$r = $db->prepare("SELECT * FROM logs;");
$r->execute();
$result = $r->fetchAll();
echo "result contains " . count($result);

If you still get 0 record in your array, perhaps there is something wrong more upstream. Let me know if you still get 0 record.

Upvotes: 2

Related Questions