denhamd2 Posted April 6, 2007 Share Posted April 6, 2007 Hi, I have a table users in my MySQL database I'm looking to select the most recently entered user record (they are indexed by the userid auto incrementing field) then I would like to echo this userid any ideas on the PHP/MySQL code for this? Many thanks in advance Quote Link to comment Share on other sites More sharing options...
paul2463 Posted April 6, 2007 Share Posted April 6, 2007 $last = mysql_last_insert_id(); //but its connection specific I think, if you close the connection you lose this info $last = "SELECT MAX(id) FROM users"; //will always work Quote Link to comment Share on other sites More sharing options...
PC Nerd Posted April 6, 2007 Share Posted April 6, 2007 well if its auto increment, you could either go through two queries, one to find the number of records on the database, and chose the highest number at the recods id which is how id do it, or you could get al the records, and loop throught ehem using while, then that last one would have been the one that you want good luck Quote Link to comment Share on other sites More sharing options...
denhamd2 Posted April 6, 2007 Author Share Posted April 6, 2007 this is the code I'm trying to use, but it just prints out all userid's, i just want it to print out the most recent one. Any ideas on how to change this code to make it work? $result = mysql_query("SELECT * FROM users ORDER BY userid ASC"); while($row = mysql_fetch_array($result)) { echo $row['userid']; } Quote Link to comment Share on other sites More sharing options...
Hughesy1986 Posted April 6, 2007 Share Posted April 6, 2007 You could just count how many there are and then echo that one, if thats what you mean. Like: <?php $query = "SELECT * FROM users"; $result = mysql_query($query) or die (mysql_error()); $total = @mysql_num_rows($result); // error check if ($total == 0) { echo "None to show <br />"; }else{ // get the last one $id = $total; $query = "SELECT * FROM users WHERE id = '$id'"; $result = mysql_query($query) or die (mysql_error()); $row = @mysql_fetch_array($result); // error check if (!$row) { echo "None to show"; }else{ // set your values here echo $total; } } ?> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.