specifying last table entry in mysql?

liunx

Guest
ive got my database sorted out, but i need to know how to refer to the last entry in a specific table, ie, the one with the highest id value, and if possible, how to refer to the five last entries. when i say refer, i mean store the data in variables. im using php to access the mysql database.well, to get the last ID that was inserted you can use mysql_insert_id()

mysql_insert_id() returns the ID generated for an AUTO_INCREMENT column by the previous INSERT query using the given link_identifier. If link_identifier isn't specified, the last opened link is assumed.

then you could take that and subtract 5 from it and then query the db again with a limit on it


select * from table limit (last_id - 5), 5

something to that effect.ok so i would have thought that every time i run this script, the id would go up by 1. but it stays at 0 - so what am i doing wrong?! obviously i have all the correct variables stored before this:


$Link = mysql_connect ($host, $user, $password);

$Query = "INSERT into $tablename values ('0', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x')";

if (mysql_db_query ($dbname, $Query, $Link)) {
print ("New record created.");
}

$Query3 = "INSERT into $tablename values ('0', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y')";

if (mysql_db_query ($dbname, $Query3, $Link)) {
print ("New record created.");
}

$Query2 = "DELETE from $tablename where user='x'";

// user is the first column after 'id'.

if (mysql_db_query ($dbname, $Query2, $Link)) {
print ("New record deleted.");
}

printf ("Last inserted record has id %d\n", mysql_insert_id());
mysql_close($Link);... and i created the table with the query:
$query = "CREATE table $tablename (id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, user TEXT, title TEXT, article TEXT, club1 TEXT, club2 TEXT, league TEXT, national TEXT, date TEXT)";ok, the mysql_insert_id() has to be after the insert.


$Link = mysql_connect ($host, $user, $password);

$Query = "INSERT into $tablename values ('0', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x')";

if (mysql_db_query ($dbname, $Query, $Link)) {
print ("New record created.");
}

$Query3 = "INSERT into $tablename values ('0', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y')";

if (mysql_db_query ($dbname, $Query3, $Link)) {
print ("New record created.");
}
printf ("Last inserted record has id %s\n", mysql_insert_id());

$Query2 = "DELETE from $tablename where user='x'";

// user is the first column after 'id'.

if (mysql_db_query ($dbname, $Query2, $Link)) {
print ("New record deleted.");
}

mysql_close($Link);
 
Back
Top