Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

query sql database to echo highest auto incremented number

Tags:

php

mysql

max

Im trying to make an sql function that displays the highest value however all the variations of the MAX function i use, still turn up with an empty image. What's going on here? how do i fix this?

//displays no image and doesn't give any errors

$result = mysql_query("SELECT MAX(id) AS id FROM people") or die (mysql_error());

//displays image 87

$result = mysql_query("SELECT  * FROM people WHERE id = 87") or die (mysql_error());

enter image description here

like image 935
ramr Avatar asked Dec 06 '12 11:12

ramr


People also ask

How do you find the highest number in SQL?

The MAX() function returns the largest value of the selected column.

How can I get auto increment number?

To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT. Creating a table, with “id” as auto-increment.

How can INSERT auto increment value in SQL query?

Obtaining the value of column that uses AUTO_INCREMENT after an INSERT statement can be achieved in a number of different ways. To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function.

How can check auto increment value in a table?

To know the current auto_increment value, we can use the last_insert_id() function. Firstly, we will create a table with the help of INSERT command. Now, we will see how many records have I inserted into my table with the help of SELECT command. Therefore, the last auto increment is 4.


1 Answers

It shouldn't display an image, it should give a result of 87.

See MAX

You could do:

select * from people order by id desc limit 0, 1 

which should give you the latest image by ID.

To make this dynamic and allow a next button you would need to store the value of image being viewed. When the next button is clicked you could then do

select * from people order by id desc limit 1, 1 //Start at row 1, bring back 1.

See MySQL Limit

You would need to use PHP to assign the values in limit and your next link though. To do this you would need to have link like so:

<a href="www.mysite.com/page?imagecount=1">Next</a>

Then using PHP you could:

<?php
    if (isset($_GET["imagecount"]))
        $next = (int)$_GET["imagecount"]; //Don't forget the (int) cast to avoid SQL injection!!!
    else
        $next = 0;

   $result = mysql_query("select * from people order by id desc limit $next, 1") or die(mysql_error());
?>

TO expand on the link, you could then make your link dynamic:

<a href="www.mysite.com/page?imagecount=<?php echo $next+1; ?>">Next</a>
like image 168
webnoob Avatar answered Oct 01 '22 22:10

webnoob