I'm trying to retrieve the id of one table A to insert into another table B. I cannot use last_insert_id() as i have not inserted anything into A. Any ideas on how to do this nicely?
$n = mysql_query("SELECT max(id) FROM tablename");
doesn't seem to work, nor does
$n = mysql_query("SELECT max(id) FROM tablename GROUP BY id");
In MySQL, this does return the highest value from the id
column:
SELECT MAX(id) FROM tablename;
However, this does not put that id into $n
:
$n = mysql_query("SELECT max(id) FROM tablename");
To get the value, you need to do this:
$result = mysql_query("SELECT max(id) FROM tablename");
if (!$result) {
die('Could not query:' . mysql_error());
}
$id = mysql_result($result, 0, 'id');
If you want to get the last insert ID from A, and insert it into B, you can do it with one command:
INSERT INTO B (col) SELECT MAX(id) FROM A;
You could descendingly order the tabele by id and limit the number of results to one:
SELECT id FROM tablename ORDER BY id DESC LIMIT 1
BUT: ORDER BY
rearranges the entire table for this request. So if you have a lot of data and you need to repeat this operation several times, I would not recommend this solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With