Richard
Richard

Reputation: 125

How to query the max id from mysql?

I have search some resources, but I still unable to make it. I would like to retrieve the data from the max id. I have some codes in .php to make query

<?php

$DB_HostName = "mysql8.000webhost.com";
$DB_Name = "";
$DB_User = "";
$DB_Pass = "";
$DB_Table = "";

$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error()); 
mysql_select_db($DB_Name,$con) or die(mysql_error()); 

$query = "SELECT MAX(id),recommendData,room,level  FROM $DB_Table";

$res = mysql_query($query,$con) or die(mysql_error());

mysql_close($con);

$rows = array();

while ($r = mysql_fetch_assoc($res))
{
    $row["maxid"] = array(
        "level" => $r["level"],
        "recommendData" => $r["recommendData"],
        "room" => $r["room"],
        "id" => $r["MAX(id)"]
    );
}

header('Content-type: application/json');

echo json_encode($row);
die;
?>

the result shows like this:

{"maxid":{"level":"2","recommendData":"8","room":"4F","id":"4"}}

the the id is right, but data of level, recommendData, room are from the first id. Do I make something wrong??

Upvotes: 0

Views: 1237

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269773

The right way to do the query is:

SELECT id, recommendData, room, level
FROM $DB_Table
ORDER BY id desc
LIMIT 1;

That is, don't do an aggregation at all.

Upvotes: 1

Nikola
Nikola

Reputation: 2132

You can try

$query = "SELECT id,recommendData,room,level  FROM $DB_Table ORDER BY id DESC LIMIT 1";

Because currently you are fetching the max id plus the other info

--

Please do not use mysql_* functions.

Use MySQLi or PDO instead

You can read on why more here

Upvotes: 2

Related Questions