Andreasschnetzer
Andreasschnetzer

Reputation: 109

Read a single value from MySQL MAX() statement with php

I want to read out the highest number of a column in my table. I try to do it with MAX() like this:

$stmt = $conn->prepare("SELECT MAX(msgconv) FROM msg");

if ( false===$stmt ) {
  die('prepare() failed: ' . htmlspecialchars($conn->error));
}

$stmt->execute();

$conv_highest = $stmt->get_result();

echo $conv_highest;

$stmt->close();

I tryed it with fetch_assoc(); aswell, but I don´t get any value into my php-variable.

EDIT:

$row = $conv_highest->fetch_assoc();
echo $row['msgconv'];

Sadly that doesn´t work either. Can somebody help me please?

Upvotes: 0

Views: 431

Answers (2)

Nick
Nick

Reputation: 147216

Your edit has got you most of the way there. The reason it doesn't work is that the field in the table is not called msgconv; you have selected MAX(msgconv) in your query so the value in $row you are looking for is $row['MAX(msgconv)']. So you have a few options, you can

$row = $conv_highest->fetch_assoc();
echo $row['MAX(msgconv)'];

or you could change the query to:

$stmt = $conn->prepare("SELECT MAX(msgconv) AS msgconv FROM msg");
// ...
$row = $conv_highest->fetch_assoc();
echo $row['msgconv'];

or you could leave the query as is and fetch a numeric array e.g.

$row = $conv_highest->fetch_row();
echo $row[0];

Upvotes: 1

Luckson MakuSimz
Luckson MakuSimz

Reputation: 79

Usually in php you can not echo an object or an array the method get_result returns a result set so you will have to iterate or open the object and get the values inside. See this link for more information. try to put $conv_highest in a print_r it may help you look inside the object e.g print_r($conv_highest). The solution might look like this

SELECT MAX(msgconv) as maximum FROM msg
      while ($row = $conv_highest->fetch_assoc()) {
        echo 'Highest: '.$row['maximum'].'<br>';
   }

Upvotes: 0

Related Questions