PHP SQL Max Basic Code to Communicate MySQL


For example, what if you need to grab the maximum numerical data from a certain MySQL column? This has several applications like:

a. In WordPress, the highest post ID is the latest post. So if you need to grab the latest Post, you can query using the highest post ID.

b. In other applications, the maximum number is the latest count, so if there is always a need to grab the latest data. All it needs is to query the maximum value in the MySQL column.

So how we are going to do this?

It is really simple:, the answer is to use the max() function of MySQL.

Another question might: So how are we going to use PHP to use MySQL max?


It is again very easy, see the code below:

<?php
//First step: Connect to MySQL database
$username = "yourdatabaseusername";
$password = "yourdatabasepassword";
$hostname = "yourdatabasehostname";
$database = "yourdatabasename";
$dbhandle = mysql_connect($hostname, $username, $password)
 or die("Unable to connect to MySQL");
$selected = mysql_select_db($database,$dbhandle)
  or die("Could not select $database");

//Second step, do a mysql query using MAX function
$result = mysql_query("SELECT max(ID) from `wp_posts`") or die(mysql_error());

//Third step, use MySQL fetch array to transfer the value of the result variable to row
$row = mysql_fetch_array($result) or die("Invalid query" . mysql_error());

//Fourth step, assign the value of array to maximum PHP variable, this now holds the maximum value
$maximum = $row['max(ID)'];

?>


Related posts: