gpt4 book ai didi

php - 清除 SQLite3 语句上的绑定(bind)似乎不起作用 (PHP)

转载 作者:搜寻专家 更新时间:2023-10-31 21:56:50 26 4
gpt4 key购买 nike

当使用准备好的语句在 PHP 中向 SQLite3 插入多行时,如果您没有为一行绑定(bind)参数,那么将插入前一行的值,即使您“清除”了行与行之间的语句。

看下面的例子:

$db = new SQLite3('dogsDb.sqlite');

//create the database
$db->exec("CREATE TABLE Dogs (Id INTEGER PRIMARY KEY, Breed TEXT, Name TEXT, Age INTEGER)");

$sth = $db->prepare("INSERT INTO Dogs (Breed, Name, Age) VALUES (:breed,:name,:age)");

$sth->bindValue(':breed', 'canis', SQLITE3_TEXT);
$sth->bindValue(':name', 'jack', SQLITE3_TEXT);
$sth->bindValue(':age', 7, SQLITE3_INTEGER);
$sth->execute();

$sth->clear(); //this is supposed to clear bindings!
$sth->reset();

$sth->bindValue(':breed', 'russel', SQLITE3_TEXT);
$sth->bindValue(':age', 3, SQLITE3_INTEGER);
$sth->execute();

尽管我希望第二行的“name”列具有 NULL 值,但该值是“jack”!

所以要么“清除”似乎不起作用(尽管它返回 true),要么我还没有真正理解它应该做什么。

如何清除 SQLite3(甚至 PDO)中插入之间的绑定(bind)?在某些行的某些字段可能具有空值的情况下插入多行的最佳方法是什么?

最佳答案

#include <sqlite3.h>
#include <stdio.h>

int main(void) {

sqlite3 *db;
char *err_msg = 0;
sqlite3_stmt *res;
sqlite3_stmt *res1;
int rc = sqlite3_open("test.sqlite", &db);

if (rc != SQLITE_OK) {

fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);

return 1;
}

char *sql = "CREATE TABLE Dogs (Id INTEGER PRIMARY KEY, Breed TEXT, Name TEXT, Age TEXT)";
rc = sqlite3_prepare_v2(db, sql, -1, &res, 0);
if (rc == SQLITE_OK) {
rc = sqlite3_step(res);

}
sqlite3_finalize(res);

char *sql1 = "INSERT INTO Dogs (Breed, Name, Age) VALUES (:breed,:name,:age);";

rc = sqlite3_prepare_v2(db, sql1, -1, &res1, 0);


if (rc == SQLITE_OK) {
printf("%d\n", sqlite3_bind_text(res1, 1, "breed1", 6, SQLITE_STATIC));
sqlite3_bind_text(res1, 2, "name1", 5, SQLITE_STATIC);
sqlite3_bind_text(res1, 3, "age1", 4, SQLITE_STATIC);
printf("%d\n", sqlite3_step(res1));
} else {

fprintf(stderr, "Failed to execute statement: %s\n", sqlite3_errmsg(db));
}
sqlite3_reset(res1);
sqlite3_clear_bindings(res1);
printf("%d\n", sqlite3_bind_text(res1, 2, "name2", 5, SQLITE_STATIC));
printf("%d\n", sqlite3_bind_text(res1, 3, "age2", 4, SQLITE_STATIC));

printf("%d\n", sqlite3_step(res1));


sqlite3_finalize(res1);
sqlite3_close(db);

return 0;
}

关于php - 清除 SQLite3 语句上的绑定(bind)似乎不起作用 (PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32917795/

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