How can the maximum value in a MySQL table be retrieved based on an ID?

To retrieve the maximum value in a MySQL table based on an ID, you can use a SQL query with the MAX() function along with a WHERE clause to specify the ID. This query will return the highest value in a specific column for a given ID.

<?php
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check connection
if($mysqli === false){
    die("ERROR: Could not connect. " . $mysqli->connect_error);
}

// Query to retrieve the maximum value based on ID
$id = 1; // Specify the ID here
$sql = "SELECT MAX(column_name) AS max_value FROM table_name WHERE id = $id";
if($result = $mysqli->query($sql)){
    if($result->num_rows > 0){
        $row = $result->fetch_array();
        echo "Maximum value for ID $id: " . $row['max_value'];
    } else{
        echo "No records found.";
    }
} else{
    echo "ERROR: Could not execute $sql. " . $mysqli->error;
}

// Close connection
$mysqli->close();
?>