Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP SQLite3::exec failure

Tags:

php

sqlite

I am having an odd error in a PHP script when it comes to SQLite3::exec, the script is able to connect to the database file with no problems and I can do select query with no problem, but when I try to do a insert query the SQLite3::lastErrorMsg has this error "unable to open database file". Here is an example of how I am trying to do this:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    add();
} else {
    mainpage();
}

function mainpage() {
    $db = db_connect();
    $results = $db->query('SELECT * FROM devices'); // Works just fine
    while (list($id, $name, $ip, $addr, $status) = $results->fetchArray());
        print "ID: $id, Name: $name, IP Address: $ip, MAC Address: $addr, Status: $status";
    }
    $db->close();
}

function add() {
    $db = db_connect();
    $query = $db->exec("INSERT INTO devices (name,ip,address,status) VALUES ('BB1', '192.168.1.5', '01:2D:45:AD:D3:A0', '1')");
    if (!$query) {
        die("Database transaction failed: " . $db->lastErrorMsg() );
    }
    mainpage();
    $db->close();
    die;
}

function db_connect() {
    class DB extends SQLite3 {
        function __construct( $file ) {
            $this->open( $file );
        }
    }
    $db = new DB('devices.db');
    if ($db->lastErrorMsg() != 'not an error') {
        print "Database Error: " . $db->lastErrorMsg() . "<br />"; //Does not get triggered
    }
    return $db;
}
?>

I know that on the add function it can connect to the database because the if statement in db_connect function is never triggered, and if I change the permissions on the devices.db file to be read only exec throws an error about writing to a read only database.

like image 477
vendion Avatar asked Dec 13 '22 08:12

vendion


1 Answers

i had the same failure, you need read/write permissions for the db file AND the directory.

like image 54
Hendrik Avatar answered Dec 25 '22 22:12

Hendrik