sqlite_last_insert_rowid
SQLiteDatabase::lastInsertRowid
(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)
sqlite_last_insert_rowid -- SQLiteDatabase::lastInsertRowid — Возвращает идентификатор последней вставленной записи
Описание
$dbhandle
)Объектно-ориентированный стиль (метод):
Возвращает идентификатор последней записи, вставленной в базу данных
dbhandle
, если таблица, в которую была вставлена
запись, содержит поле с автоинкрементом.
Поля с автоинкрементом в SQLite объявляются как INTEGER PRIMARY KEY.
Список параметров
-
dbhandle
-
Ресурс базы данных SQLite, полученный из функции sqlite_open() в случае использования процедурного подхода. Этот параметр не требуется при использовании объектно-ориентированного подхода.
Возвращаемые значения
Возвращает идентификатор записи в виде целого числа.
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с базами данных
- Расширения для работы с базами данных отдельных производителей
- SQLite
- sqlite_array_query
- sqlite_busy_timeout
- sqlite_changes
- sqlite_close
- sqlite_column
- sqlite_create_aggregate
- sqlite_create_function
- sqlite_current
- sqlite_error_string
- sqlite_escape_string
- sqlite_exec
- sqlite_factory
- sqlite_fetch_all
- sqlite_fetch_array
- sqlite_fetch_column_types
- sqlite_fetch_object
- sqlite_fetch_single
- sqlite_fetch_string
- sqlite_field_name
- sqlite_has_more
- sqlite_has_prev
- sqlite_key
- sqlite_last_error
- sqlite_last_insert_rowid
- sqlite_libencoding
- sqlite_libversion
- sqlite_next
- sqlite_num_fields
- sqlite_num_rows
- sqlite_open
- sqlite_popen
- sqlite_prev
- sqlite_query
- sqlite_rewind
- sqlite_seek
- sqlite_single_query
- sqlite_udf_decode_binary
- sqlite_udf_encode_binary
- sqlite_unbuffered_query
- sqlite_valid
Коментарии
I have noticed that this will still return an insert id even if a table has not been assigned a primary key or has not been assigned a primary key correctly. If the table was not created correctly sqlite_last_insert_rowid() will return its internal row id, which is probably not what you want. The correct way to establish a primary key migh look something like this look something like this:
create table some_table (id INTEGER PRIMARY KEY, some_field varchar(10))
Then you can try:
insert into some_table (some_field) values ('bob')
You will see that an id will be automatically generated and
calling sqlite_last_insert_rowid() will return the expected value
Note that if you insret a few rows in your table, say rowid 1-5, and then delete 2,3 and 4, you will be left with the rowids 1 and 5, not 1 and 2. This may seem basic to anyone with database experience, but I had to check it out with a GUI tool before I figured this one out. Anyway, what it boils down to is that sometimes your rowid will be greater than the number returned by the SQLite COUNT (*) function.
Note that you don't need to create a primary key for your table. In the absence of an integer primary key, SQLite simply uses an internal key called "RowID" or "OID".
It has all of the features of a normal integer primary key(auto-incrementing, returned by sqlite_last_insert_rowid(), accessible via SELECT, etc), except that it's handled better by SQLite and doesn't require the extra characters in the "CREATE" command.
If you just want a primary key as an auto-incrementing ID for your rows, save yourself the trouble and just use "OID" instead.
Also, according to the SQLite website, the id returned is for the last insert in the current *connection*, not just database. This means that if there are two connections to the same database at the same time, and both perform "INSERT", each can get it's own inserted rowid later, so basically this is thread-safe(So long as no-one calls "REINDEX").