Forum Moderators: coopster

Message Too Old, No Replies

MySQL Query

Get the latest added record in a table

         

Grenz

9:39 am on Nov 30, 2009 (gmt 0)

10+ Year Member



Hi all
Im having a script, where the last inserted record should be updated.
This is what I have so far:

$con = mysql_connect("localhost","dMyDB","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("MyDB", $con);

$result = mysql_query("SELECT id FROM table_name");

while ($row = mysql_fetch_array($result)) {

$max_id=$row['id'];

mysql_query("UPDATE table_name SET name='testname' WHERE id='$max_id'");

}

mysql_close($con);

This code is working, but it selects all ID's and update the name. I have tried:

SELECT MAX(id) FROM table_name
SELECT TOP 1 FROM table_name

But none of that worked.

What am I doing wrong? And can anyone help me out?

Thanks in advance

Grenz

10:20 am on Nov 30, 2009 (gmt 0)

10+ Year Member



Hi all

I figured it out myself.

It should be: SELECT id FROM table_name ORDER BY id DESC LIMIT 1

rocknbil

6:37 pm on Nov 30, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



And done so in under an hour! :-)

PHP coders like to use mysql_insert_id() [us2.php.net] but I use that one as well, especially if there is no previous "query."