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



PHP







In this article, we show how to get the minimum 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 cheapest or lowest of anything.

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



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

Example with Full PHP Code

Now we show an example of code that finds the minimum 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 minimum value of all the rows in the orders column of this table.



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

If you look at the table, the lowest value is 2.25. Thus, this is the minimum 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 MIN of the orders column AS minimum from the CustomerOrders table.

The minimum can be seen as the imaginary row that holds the minimum 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 minimum row and store it in the variable $minimum.

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

Actual PHP Output