gpt4 book ai didi

php - 如何在 PHP 上提交 SQLite3 更新?

转载 作者:行者123 更新时间:2023-12-03 17:32:31 26 4
gpt4 key购买 nike

我正在尝试在 PHP 中使用 SQLite3,在我需要执行更新之前一切都很好。我想我错过了 COMMIT,但我找不到如何做的方法。

我的代码是:

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

我想要的是从数据库中读取所有问题,并将 resposta 列中的答案与 POST 接收到的 $respostes 变量中的答案进行比较。这也很好用。然后,如果答案正确,我需要将此正确性存入数据库,将此行的 correcta 列设置为 1。如果我显示查询,然后将其放在 SQLite3 控制台上,它可以正常工作,但是当我在 PHP 上重新检查它时,它一直为 0,即使 $conn->changes() 显示 UPDATE影响 1 行。

我检查了所有我能想到的东西,boxberry.db 文件对任何用户都是可读和可写的,我尝试用默认的 SQLITE3_OPEN_READWRITE 打开它,我试图添加一个 COMMIT 的执行,或者甚至把它放在相同的 exec 行用分号分隔...没有错误被抛出,但值没有改变。

将 SQLite 与 Python 结合使用,我发现我需要在更新后提交,但我找不到在 PHP 中执行此操作的方法。

此脚本返回如下内容:{“canvis”:1,“tmp”:0}这意味着它应该是 1 个变化,但是当应该是 1 时,数据库中的值仍然是 0。

最佳答案

我建议为此使用 PDO 而不是 SQLite3 扩展:

$dbh = new PDO('sqlite:/home/pi/boxberry/boxberry.db');

$res = $dbh->query('SELECT numero, resposta FROM preguntes WHERE NOT correcta');
foreach($res as $resposta)
{
if(FALSE !== strstr(strtolower($respostes), strtolower($resposta['resposta'])))
{
$updstmt = $dbh->prepare('UPDATE preguntes SET correcta = 1 WHERE numero = :numero');
$updstmt->bindParam(':numero', $resposta['numero']);
$updstmt->execute();
$return['canvis'] = $updstmt->rowCount();

$stmt = $dbh->prepare('SELECT correcta FROM preguntes WHERE numero = :numero');
$stmt->bindParam(':numero', $resposta['numero']);
$stmt->execute();
$return['tmp'] = $stmt->fetchAll();
}
}

这是未经测试的,但应该可以直接替代 OP 的示例代码。

通过使用 PDO,您不必担心 SQLite 中的提交语句,因为它们是自动处理的。如果您想要能够提交或回滚一组特定的查询,您可以使用 PDO::beginTransactioncommit()/rollBack()

关于php - 如何在 PHP 上提交 SQLite3 更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12007382/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com