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 Link to comment https://forums.phpfreaks.com/topic/45864-phpmysql-question/ 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 Link to comment https://forums.phpfreaks.com/topic/45864-phpmysql-question/#findComment-222814 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 Link to comment https://forums.phpfreaks.com/topic/45864-phpmysql-question/#findComment-222815 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']; } Link to comment https://forums.phpfreaks.com/topic/45864-phpmysql-question/#findComment-222820 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; } } ?> Link to comment https://forums.phpfreaks.com/topic/45864-phpmysql-question/#findComment-222823 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.