How to Get the Maximum Value of a Column of a MySQL Table Using PHP



PHP







In this article, we show how to get the maximum value of a column of a MySQL table using PHP.

This could be very valuable for a wide number of applications.

This could be used if you're looking, for instance, for the absolute expensive or highest of anything.

The general format of the PHP code to find the maximum value of all the rows of a column of a MySQL table is shown below.



The above code finds the maximum value from the column_name column from the table.

Example with Full PHP Code

Now we show an example of code that finds the maximum value of a column of a MySQL table.

Below is the table used for this example.

MySQL CustomerOrders Table

This represents a customer's order. For example, it can be a shopping cart and these are all the items in the shopping cart.

Below is the full PHP code to get the maximum value of all the rows in the orders column of this table.



So the above code finds the maximum value of all the rows of the orders column.

If you look at the table, the highest value is 9.00. Thus, this is the maximum value in the column.

So to explain the code a little, we first connect to the database.

Then we query the database using the $result variable. This $result variable queries the database by getting the MAX of the orders column AS maximum from the CustomerOrders table.

The maximum can be seen as the imaginary row that holds the maximum value of all rows of the orders column.

We then use the mysql_fetch_assoc() function to get this row. We store it in the variable $row.

Lastly, we get the value in this maximum row and store it in the variable $maximum.

In the last line of the PHP code, we echo out the maximum value.

Actual PHP Output


This is the maximum value: 9.00




Related Resources

How to Get the Sum of All Rows of a Column of a MySQL Table Using PHP

How to Get the Average of All Rows of a Column of a MySQL Table Using PHP

How to Get the Minimum Value of a Column of a MySQL Table Using PHP

HTML Comment Box is loading comments...