0

I am inserting record into database using the insert query as

INSERT INTO task_record(assigned_by,handle_by) VALUES('$assigned_by', '$handle_by')

adding this record assign a unique ID to the each record i want to get that ID as soon as the record is inserted. Is there any simple way to modify the query or i have to use one more query of select which is not a fine option

som
  • 4,650
  • 2
  • 21
  • 36
  • 4
    `SELECT LAST_INSERT_ID()` for direct sql, and lookup the api specific info. – DevZer0 Aug 05 '13 at 10:56
  • http://stackoverflow.com/questions/897356/php-mysql-insert-row-then-get-id – ale Aug 05 '13 at 10:56
  • i have tried with this `echo $id = mysql_insert_id();` i have right this line after the data is inserted but its returning 0 – Abdul Qadeer Aug 05 '13 at 11:00
  • Show us more of your PHP code, including the actual code used to make the query. (there are several possible answers to your question; we need to see more of your code in order to know which one is correct) – Spudley Aug 05 '13 at 11:22

2 Answers2

0

Try with $this->db->insert_id() like

echo "The Last Insert Id is ".$this->db->insert_id();

Or like

echo "The Last Insert Id is ".$this->insert_id();

Or even simply

echo "The Last Insert Id is ".mysql_insert_id();

But try to avoid using mysql_* functions due to they are deprecated.Instead use either mysqli_* functions or PDO statements.

EDIT:

$query = "SELECT LAST_INSERT_ID() task_id";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
    $id = $row['task_id'];
}
echo $id;
GautamD31
  • 28,552
  • 10
  • 64
  • 85
0

If your interfacing with mysql directly execute SELECT LAST_INSERT_ID() after the insert query.

with the now obsolote mysql extension you could execute mysql_insert_id();

with the mysql improved extension use mysqli_insert_id();

DevZer0
  • 13,433
  • 7
  • 27
  • 51