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

时间:2015-10-03 00:50:03

标签: php sqlite prepared-statement prepare

使用预准备语句在PHP中向SQLite3插入多行时,如果没有为行绑定参数,那么即使您“清除”行之间的语句,也会插入上一行的值。 / p>

请看以下示例:

$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'而不是!

所以'clear'似乎不起作用(虽然它返回true)或者我还没有真正理解它应该做什么。

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

1 个答案:

答案 0 :(得分:0)

#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;
}