1

I've been looking around but most of the tutorials are showing the mysql_insert_id() but it's on the same document. I'm wondering if there is a way where you can get the last id of a column and echo it out.

$image = mysql_query("SELECT * FROM images WHERE id=$id");
$image = mysql_fetch_assoc($image) or die(mysql_error());

$image = $image['image'];

header("Content-type: image/jpeg");

echo $image;

This is my code that gets the image from the database and makes the blob into a id?=1 which is the picture but as php. That is a uploader from another php document but I'm typing to output the last id from that column on another page (Not the picture but the number for statistics)

A bit of code that could do that would be very helpful.

Cyclonecode
  • 29,115
  • 11
  • 72
  • 93
Onz
  • 15
  • 1
  • 4
  • On a side note, I really suggest you stop using the old mysql library and switch to PDO or at least mysqli for php. You want to use a prepared statement for the $id in the where clause to protect against injection. – Ray Feb 14 '12 at 22:31

5 Answers5

5

This would grab the row with the highest ID:

$result = mysql_query("SELECT MAX(id) FROM images");
$row = mysql_fetch_row($result);
// $row[0] contains the value of the highest id
Cyclonecode
  • 29,115
  • 11
  • 72
  • 93
1
SELECT * FROM images ORDER BY id DESC LIMIT 1
Rene Pot
  • 24,681
  • 7
  • 68
  • 92
malonso
  • 2,247
  • 1
  • 21
  • 33
  • 2
    `select max(id) from images` is far easier and lest wasteful. – Marc B Feb 14 '12 at 22:23
  • @MarcB - Sorry, you are right. I misunderstood the post. I thought they were saying they were getting the image out of the db. max(id) is ABSOLUTELY the way to go. Thanks for pointing that out! – malonso Feb 15 '12 at 00:56
1

Immediately after the query is done, use:

$newId = mysql_insert_id();

It will return the last inserted id

Ray
  • 40,256
  • 21
  • 101
  • 138
0

With PDO How to return max(id) in pdo

$sql_lastid = $pdo -> prepare("SELECT MAX(id) as max_id FROM *table*");
$sql_lastid -> execute();
$id     = $sql_lastid -> fetch(PDO::FETCH_ASSOC);
$lastid = $id['max_id'];
pixelDino
  • 105
  • 2
  • 9
0
$query = "SELECt MAX(id) FROM images";

$result = mysql_query($query);
$row = mysql_affected_rows($result);

echo $row[0];
kapex
  • 28,903
  • 6
  • 107
  • 121
xxxo_tryme
  • 213
  • 1
  • 2
  • 12