tipiwiny tipiwiny - 1 year ago 61
SQL Question

PHP-return maximum value of any table and column

I want to create a function in PHP that return a maximum value ,with the particularity that the function receives as parameters the table name and column name where I want to apply the filter maximum value.
For example:

function mymaxvalue($nametable,$namecolum)

global $con;
global $valueMax;
$sql = "SELECT MAX($namecolum) FROM '$nametable'";

$result = mysql_query($sql, $con);
while ($row = mysql_fetch_array($result)) {

echo $temperaturaMax = $row['MAX($namecolum)'] ;



Unfortunately, when I call the function, it does not work. Thanks for you help.

Answer Source

First of all, don't use mysql_* functions as they deprecated and completely removed in PHP 7.

Two things:

1) Remove single quote from table name.

Corrected SQL:

$sql = "SELECT MAX($namecolum) FROM $nametable";

2) Use double quotes as variables inside single quotes are not parsed:

echo $temperaturaMax = $row["MAX($namecolum)"];


Second approach:

Use alias:

Corrected SQL:

$sql = "SELECT MAX($namecolum) as maxVal FROM $nametable";
echo $temperaturaMax = $row['maxVal'];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download