Page 1 of 1
Selecting the last row from Mysql database?
Posted: Sat Feb 01, 2003 7:19 am
by mikebr
I am trying to find out how I can get the column entries for the last row entered in a database, for example I update exchange rate entries each day in the database but when the application needs to get the up to date exchange rate I want it to use the date from the last entry. I use a date column for when the exchange rates are entered but feel it would be quicker to just pull the date from the last entry rather than performing a search on the most up to date.
Any help appriciated
Thanks
check
Posted: Sat Feb 01, 2003 9:49 am
by AVATAr
check on the manual: mysql_affected_rows
Posted: Sat Feb 01, 2003 11:11 am
by mikebr
Maybe I didn't make what I was trying to do clear or that I don't quite understand how mysql_affected_rows can help me, I looked up the manual as I did before but still can't find out how to do the following, I am writing a simple script to get the last ID entry from a table , doesn't matter if it was made 5 seconds ago or 5 hours ago, basically I am doing this:
$sql = "SELECT * FROM table WHERE ID = 'the_last_ID_value_entered'";
ID is an auto_increment column but at times I could make a deletion from the table I could have used count(*) to count the entries then make the election as follows:
$sql = "SELECT count(*) FROM rates";
etc, etc
$num_rows = $rows[0];
$sql = "SELECT * FROM table WHERE ID = '$num_rows'";
so hence I need to find a way of taking the ID or better still all the column entries from the last entry that was made, which could have been anytime within the last 24 hours.
Thanks
Posted: Sat Feb 01, 2003 11:31 am
by Stoker
no need to do two queries, if you are looking for the last added record you can just do something like
SELECT max(myID) FROM myTable GROUP BY myID
would give you the id of the last (highest-numbered-id) , if you want some of the other columns at the same time you can include those as well, something like
SELECT max(myID) AS myID, somecol, someothercol, blah, duh FROM myTable GROUP BY myID
problem
Posted: Sat Feb 01, 2003 12:08 pm
by AVATAr
The problem with using a select statement: if another user inserts a row... you loose your insert id...
you can use a function called: mysql_insert_id() that return the id of the last query you use, for instance:
Code: Select all
<?php
mysql_query($sql, $conn);
$last_id= mysql_insert_id(); //you have the last id used.
?>