nkcmr
nkcmr

Reputation: 11000

How would you get an auto_increment value on an insert query?

So, I was wondering if you were to launch this query:

INSERT INTO users (name, gender, location) VALUES ('Ricky-Bobby', 'm', 'Daytona Beach, FL');

And suppose that users has another auto-incrementing columns for the primary key, how would you be able to get the value of that primary key without launching another query?

Upvotes: 2

Views: 5299

Answers (4)

Robin Castlin
Robin Castlin

Reputation: 10996

Codeigniter simplifies the MySQL query SELECT LAST_INSERT_ID() through the function $this->db->insert_id().

Although this is a query, it's a very light one that won't be a performance issue. One thing to have in note is this:

  • If you want the ID on the row you inserted; $this->db->insert_id()
  • If you want the auto_increment value, that is the next value that an INSERT will have as id, simply $this->db->insert_id() + 1

Upvotes: 3

dm03514
dm03514

Reputation: 55962

codeigniter makes this available with $this->db->last_insert_id()

http://ellislab.com/codeigniter/user-guide/database/helpers.html

Upvotes: 3

flowfree
flowfree

Reputation: 16462

You can combine LAST_INSERT_ID() with your query:

INSERT INTO users (name, gender, location) VALUES ('Ricky-Bobby', 'm', 'Daytona Beach, FL');
SELECT LAST_INSERT_ID();

Upvotes: 1

svrcoder
svrcoder

Reputation: 96

You could use this if you are using PDO

http://php.net/manual/en/pdo.lastinsertid.php

Upvotes: 0

Related Questions