Reputation: 3912
I have my table columns set like this:
likes(id, like_message, timestamp)
id
is the primary key that is auto incrementing. This is the SQL that I use to add a row:
$sql = "INSERT INTO `likes` (like_message, timestamp)
VALUES ('$likeMsg', $timeStamp)";
Everything works, but now I need to throw back the id
attribute of the newly inserted row. For example, if I insert a row and the id
of that row is 13
, I need to echo out 13
so my AJAX request can pick that up and use it.
Any help would be appreciated, as well as related code samples. Thanks :)
Upvotes: 1
Views: 5321
Reputation: 15409
This page will give you lots of good information on the problem:
In PHP:
mysql_query("INSERT INTO foo(blah) values ('blee')");
echo mysql_insert_id();
In SQL:
INSERT INTO foo (blah) VALUES('blee');
LAST_INSERT_ID() --now contains your last inserted id
Upvotes: 4
Reputation: 11068
$id = mysql_insert_id();
http://php.net/manual/en/function.mysql-insert-id.php
Upvotes: 9