I’m trying to use SQLite3 in PHP, and everithing was fine until I needed to perform an UPDATE.
I supose I miss a COMMIT, but I don’t find the way on how to do it.
My code is:
$respostes = $_POST['respostes'];
$return = array();
$conn = new SQLite3( '/home/pi/boxberry/boxberry.db', SQLITE3_OPEN_READWRITE );
$res = $conn->query( 'SELECT numero, resposta FROM preguntes WHERE NOT correcta' );
while( $resposta = $res->fetchArray( SQLITE3_ASSOC ) )
{
if( strstr( strtolower( $respostes ), strtolower( $resposta['resposta'] ) ) !== FALSE )
{
$conn->exec( 'UPDATE preguntes SET correcta = 1 WHERE numero = ' . $resposta['numero'] );
$return['canvis'] = $conn->changes();
$conn->exec( 'COMMIT' );
$res = $conn->query( 'SELECT correcta FROM preguntes WHERE numero = ' . $resposta['numero'] );
$tmp = $res->fetchArray( SQLITE3_ASSOC );
$return['tmp'] = $tmp['correcta'];
}
}
.... more stuff ...
echo json_encode( $return );
What I want is to read all the questions from the database, and compare the answers from the resposta column with the answers within the $respostes variable received by POST. That also works fine.
Then, if the answer is correct, I need to put this correctness to the database, setting the correcta column for this row to 1.
If I show the query and then I put it on the SQLite3 console it works properly, but when I recheck it on PHP it keeps being 0, even when $conn->changes() shows that the UPDATE affected 1 row.
I checked everithing I can figure, the boxberry.db file is readable and writable by any user, I tried oppening it with SQLITE3_OPEN_READWRITE that should be as default, I tried to add an execution of a COMMIT, or even put it in the same exec line sepparating both with semicolons… No error is thrown, but the values doesn’t change.
Using SQLite with Python I found that I need to COMMIT after the UPDATE, but I can’t find the way to do it in PHP.
This script returns something like:
{“canvis”:1,”tmp”:0}
That means it should be 1 change, but then the value in the database is still 0 when should be 1.
You shouldn’t need to manually commit changes with the
SQLite3extension but you might need to make the directory that contains the database file writable (probably set it so that your webserver software has write-rights). Just making the database file itself writable is not always enough for SQLite.