-1

I am new to php. I wrote an sql query in my php file to return the most popular hour from a table.

$result = mysql_query("SELECT HOUR(dtime) as Hr,COUNT(*) AS Cnt
                       FROM lewis_locations
                       GROUP BY Hour(dtime)
                       ORDER BY Cnt DESC
                       LIMIT 1");  
 if (mysql_num_rows($result) > 0) {
        // looping through all results
        // products node
    $response["lewis_locations"] = array();
    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $stop = array();
        $stop["id"] = @$row["id"];
        $stop["name"] = @$row["name"];
        $stop["dtime"] = $row["dtime"];

        // push single product into final response array
        array_push($response["lewis_locations"], $stop);
 }

But when I try to get the result I get the error:

Notice: Undefined index: dtime

The error is located in this line:

$stop["dtime"] = $row["dtime"];

I understand if i suppress the error with the @ operator like so:

$stop["dtime"] = @$row["dtime"];

the error will go away. But it does not fix my problem as I am left with a Null vaule result. I have used this php code with other sql queries and I have been successful in getting the right value. So why wouldn't the @ operator work this time? I have researched what the @ operator does but I do not understand its inconsistency.. And is there a quick fix for this?

Ian Patrick Hughes
  • 10,386
  • 3
  • 31
  • 37
Cillín
  • 187
  • 1
  • 13
  • You only selected "Hr" and "Cnt" in your query, so only $row["Hr"] and $row["Cnt"] exist. You have each column you wish in your select statement. – Random Jul 27 '15 at 16:05

1 Answers1

0

The only columns or values you are selecting in your query: SELECT HOUR(dtime) as Hr,COUNT(*) AS Cnt are "Hr" and "Cnt". If you want id, name and dtime, you need to select them.

Jessica
  • 7,075
  • 28
  • 39