Joomla!, Wordpress tips for building your site

How to get last insert auto increment id.

Published on| February 10th, 2010 | No Comment.

If you set ‘AUTO_INCREMENT’ to attribute of the table column , its column will increment automatic when records is inserted into the table. And its increment number is unique. Moreover, I think that you often specify such information for primary key (PRIMARY KEY).

You will not consider this column information usually. However, when you want to take out inserted information, you might feel it to the necessity.

How to get last insert auto increment id?
It is easy. If you execute the following SQL, MySQL will answer last insert auto increment id.

select last_insert_id() [from table name];

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
> mysql -h=xxx -u=username -p=**** dbname
 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 465
Server version: 5.1.36-community MySQL Community Server (GPL)
 
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
 
mysql> CREATE TABLE `test_autoincrement` (
    ->   `id` int unsigned NOT NULL AUTO_INCREMENT,
    ->   `value` text NOT NULL,
    ->   PRIMARY KEY (`id`)
    -> ) DEFAULT CHARSET=utf8;
Query OK, 0 rows affected (0.06 sec)
 
mysql> insert into test_autoincrement(value) values('sample-data...');
Query OK, 1 row affected (0.02 sec)
 
mysql> select last_insert_id() from test_autoincrement;
+------------------+
| last_insert_id() |
+------------------+
|                1 |
+------------------+
1 row in set (0.02 sec)
 
mysql> insert into test_autoincrement(value) values('sample-data2...');
Query OK, 1 row affected (0.03 sec)
 
mysql> select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
|                2 |
+------------------+
1 row in set (0.00 sec)
 
mysql>
xxx: mysql host name
username: username to login
****: password to login
dbname: database name to use

On Line 19 or 30, get last insert id, and displayed.





You might also like:


Comments

Leave a Reply








Transrator

Recent Posts

Categories

Tag Cloud

execute remove フロントページ 投稿ページ トップページ install WIndows Note Convert META generator 日付 donwload file manage multibyte utf-8 unicode shiftjis euc console サイトマップ 問題 ParmaLink Redirect パーマリンク はみ出る pre テンプレート テーマ タグクラウド マルチランゲージ リダイレクト PHP(タグ) タグ table control HTML(タグ) コマンド 国際化(翻訳) SQLite(タグ) MySQL(タグ) qTranslate プラグイン(タグ) Wordpress(タグ)

Links

Site Description

Joomla!, Wordpress as CMS using a site building, site management, software usage to describe the development tips.

  • はてなブックマークへ追加する
  • Facebookでシェアする
  • twitter でつぶやく
  • Google Plusでシェアする
  • Pocketでシェアする
ページトップへ