Home > Software design >  php displayes wrong data from db
php displayes wrong data from db

Time:05-12

I am trying to display the highest temperature and the day that temperature was recorded. It displays the correct temperature but the wrong date. I don't know if I am going crazy, but I am quite sure it worked just fine before. Here is the query request.

$statment = $pdo->prepare('SELECT MAX(temperature), date FROM 4pmweather ');
$statment->execute();
$products = $statment->fetchAll(PDO::FETCH_ASSOC);

$max_temp = $products[0]['MAX(temperature)'];
$max_temp = floatval(round($max_temp,1));
$date_of_max_temp = $products[0]['date'];

echo '<pre>';
var_dump($products);
echo '</pre>';

Here is what var_dump() returns as I said it shows the right temperature but the wrong date. i don't know if that matters but I am using phpmyadimin.

array(1) {
      [0]=>
      array(2) {
    ["MAX(temperature)"]=>
    float(27.05)
    ["date"]=>
    string(19) "2022-04-30 16:59:02"
  }
}

[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/JDnzl.png

CodePudding user response:

Try something this:

$statment = $pdo->prepare('SELECT temperature, date FROM 4pmweather WHERE temperature=(SELECT MAX(temperature) FROM 4pmweather)');

Otherwise you will get the max value from the temperature column and the first id.

Just note that if max temperature is not unique it might return multiple rows. Then you could add LIMIT 1 to the query:

SELECT temperature, date FROM 4pmweather WHERE temperature=(SELECT MAX(temperature) FROM 4pmweather) LIMIT 1
  • Related