我有这个当前的 SQLite 表:
CREATE TABLE Goal (
id INTEGER PRIMARY KEY,
Name CHAR(32) NOT NULL,
Image CHAR(256),
Target INTEGER NOT NULL,
Priority CHAR(32) NOT NULL
);
我正在尝试通过 PHP 创建一个整数 ID,如下所示:
$query = 'INSERT OR IGNORE INTO Goal (Name, Image, Target, Priority) VALUES'; // Query to insert goal-related info into Goal table
$query .= "('" . $name . "', '" . $image . "', '" . $target . "', '" . $priority . "');";
$addGoalDB -> makeQuery( $query );
$query = 'SELECT last_insert_rowid()';
$result = $addGoalDB -> makeQuery( $query );
$id = $result -> fetchArray(SQLITE3_ASSOC);
$id = $id['id'];
$query = 'INSERT OR IGNORE INTO Users_Goal (Email, id) VALUES';
$query .= "('" . $_SESSION['username'] . "', '" . $id . "');";
$addGoalDB -> makeQuery( $query );
但是不断得到一个 undefined index 错误
$id = $id['id'];
我假设查询是错误的,但找不到我的问题所在。此链接:http://alvinalexander.com/android/sqlite-autoincrement-insert-value-primary-key使它看起来很简单,但不适用于我的代码。对此,我将不胜感激。
最佳答案
您正在尝试读取名为“id
”的列。但是列是根据您在 SELECT
子句中编写的内容命名的,因此实际的列名称类似于 last_insert_rowid()
。
给列一个合适的名字:
$query = 'SELECT last_insert_rowid() AS id';
关于php - SQLite 通过 PHP 自动增加字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43394758/