sunman
sunman

Reputation: 89

Undefined index for max function not working in php

I am facing problem with my php code. I have already tried Stack Overflow suggestions, but that code doesn't properly work. Here I am using max and min functions. Also trying function mysql_fetch_rows() and mysql_fetch_assoc(). It shows me the error undefined index:facilities_total in line... I also point out my error in below code. Please suggest how to correct this.

This is my php with mysql query

$sqlMax= "SELECT projects_detail.Project_name,max(facility_rating.facilities_total) 
    AS MAX_FACILITIES_TOTAL 
    FROM facility_rating LEFT OUTER JOIN projects_detail
    on facility_rating.project_id = projects_detail.project_id
    group by facility_rating.facilities_total DESC LIMIT 1";
$resultMax=mysql_query($sqlMax);
echo "<table border cellpadding=3>";
while($rowsMax=mysql_fetch_array($resultMax)){
    echo "<tr>"; 
    echo "<td>".$rowsMax['Project_name'] . "</td> ";
    echo "<td>".$rowsMax['facilities_total'] . "</td> "; //error undefined index:facilities_total
    echo "</tr>";
}
echo "</table>";

Upvotes: 0

Views: 795

Answers (3)

sshet
sshet

Reputation: 1160

As seen you are giving alias in your query and you are using column names in your php code:

$sqlMax= "SELECT projects_detail.Project_name,max(facility_rating.facilities_total) 
    AS MAX_FACILITIES_TOTAL 
    FROM facility_rating LEFT OUTER JOIN projects_detail
    on facility_rating.project_id = projects_detail.project_id
    group by facility_rating.facilities_total DESC LIMIT 1";
$resultMax=mysql_query($sqlMax);
echo "<table border cellpadding=3>";
while($rowsMax=mysql_fetch_array($resultMax)){
    echo "<tr>"; 
    echo "<td>".$rowsMax['Project_name'] . "</td> ";
    // Fix: Changed 'facilities_total' to 'MAX_FACILITIES_TOTAL' below.
    echo "<td>".$rowsMax['MAX_FACILITIES_TOTAL'] . "</td> "; //error undefined index:facilities_total
    echo "</tr>";
}
echo "</table>";

Upvotes: 2

IMSoP
IMSoP

Reputation: 97968

Your SQL names the output column here:

 AS MAX_FACILITIES_TOTAL

So the PHP variable you want will be

$rowsMax['MAX_FACILITIES_TOTAL']

Upvotes: 0

potashin
potashin

Reputation: 44601

Try this :

echo "<td>".$rowsMax['MAX_FACILITIES_TOTAL'] . "</td> ";

Instead of

echo "<td>".$rowsMax['facilities_total'] . "</td> ";

In your sql your are using alias for facilities_total, so rows are fetched with field name MAX_FACILITIES_TOTAL instead of facilities_total.

Upvotes: 1

Related Questions