For the record, the problem was that, in addition to forgetting the fetch (which was pointed out by @rray), also had an error in the query as it was passing the wrong field name.
After I put the
$query = $mysqli->query($sql) or die($mysqli->error);
at @rray’s suggestion, error appeared:
Unknown column 'id' in 'order clause'
So it was just to include the while with the fetch, and correct the field name.
Stayed like this:
require_once "../../models/conex.php";
$sql = "SELECT * FROM tabela ORDER BY idcerto DESC LIMIT 1";
$query = $mysqli->query($sql) or die($mysqli->error);
while ($dados = $query->fetch_assoc()) {
print_r($dados['idcerto']);
}
UPDATE
Following @Danielomine’s guidance in the comments, I changed the while for if, for two reasons:
- as only return a result, do not need the
while;
- putting the
if it checks if the result does not return empty;
The standard code:
require_once "../../models/conex.php";
$sql = "SELECT * FROM tabela ORDER BY idcerto DESC LIMIT 1";
$query = $mysqli->query($sql) or die($mysqli->error);
if ($dados = $query->fetch_assoc()) {
$idcerto = (int)(($dados['idcalc']) + 1);
echo $idcerto;
}
else{
echo "erro na obtenção da id";
}
?>
You are closing the connection before catching the result, missed the
fetch(). Or your real query has some error, because the idea is to sort by id in descending order and return a line.– rray
Don’t forget to see if there are any mistakes at the consulate
$query = $db->query($sql) or die($db->error);– rray
@rray,
$dbin case is the connection link? in my case$mysqli?– gustavox
@rray besides forgetting the
fetch, had an error in the same query, was passing the name of the wrong field. After I put the$query = $mysqli->query($sql) or die($mysqli->error);that you suggested, appeared the errorUnknown column 'id' in 'order clause'and then bingo.... It went like this:require_once "../../models/conex.php";

$sql = "SELECT * FROM tabela ORDER BY idcerto DESC LIMIT 1";
$query = $mysqli->query($sql) or die($mysqli->error); while ($dados = $query->fetch_assoc()) {
 print_r($dados['idcerto']);
}– gustavox
Creates an answer,
– rray