1

I'm trying to get the id of the last record inserted into a MySQL database using MAX(id). I can't figure out why my query is not returning any results. Is there something wrong with my PHP?Tthe query works if I try it inside phpmyadmin.

include("db_conx.php"); //Connect to db mysqli
$sql = "SELECT MAX(id) FROM tbl_uploads";  
$result = $db_conx->query($sql);
$row = $result->fetch_assoc();
echo 'last_id: '.$row['id'];
JulianJ
  • 1,259
  • 3
  • 22
  • 52

4 Answers4

2

use an alias for get the value

  $sql = "SELECT MAX(id) as max_id FROM tbl_uploads";  
  $result = $db_conx->query($sql);
  $row = $result->fetch_assoc();
  echo 'last_id: '.$row['max_id'];
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
2

Use MAX(id) as id in select query

include("db_conx.php"); //Connect to db mysqli
$sql = "SELECT MAX(id) as id FROM tbl_uploads";  
$result = $db_conx->query($sql);
$row = $result->fetch_assoc();
echo 'last_id: '.$row['id'];
Rafiqul Islam
  • 1,636
  • 1
  • 12
  • 25
1

you can use this built in function for get last insert id

$last_id = mysqli_insert_id($conn);

if you want to get max record id from your db and if id this your primary key then you can use this code

$sql = "SELECT id FROM tbl_uploads order by id desc";  
$result = $db_conx->query($sql);
$row = $result->fetch_assoc();
echo 'last_id: '.$row['id'];

and if you want to get specific max record then use this code. if id your filed then you can use this code . you use alias for get record

$sql = "SELECT MAX(id) as max_id FROM tbl_uploads";  
$result = $db_conx->query($sql);
$row = $result->fetch_assoc();
echo 'last_id: '.$row['max_id'];
Shafiqul Islam
  • 5,570
  • 2
  • 34
  • 43
0

Try with this :

$sql = "SELECT * FRON tbl_uploads ORDER BY id DESC LIMIT 1";

It will output your id.

DamiToma
  • 921
  • 3
  • 9
  • 27