How to put the last row number of a MySQL table in a variable

2

I would like to know how to get the last row of a MySQL table, and put this number inside a PHP variable.

I tried this way:

require_once "../../models/conex.php";

$sql = "SELECT * FROM tabela ORDER BY id DESC LIMIT 1";
$query = $mysqli->query($sql);
$ultimaLinha = $query;
$mysqli->close();

But var_dump returns boolean false ...

    
asked by anonymous 19.09.2015 / 08:50

3 answers

4

Just to note, the problem was that in addition to forgetting 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 the suggestion of @rray, the error appeared:

  

Unknown column 'id' in 'order clause'

Then just include while with fetch , and correct the field name.

It looks 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 the guidance given by @DanielOmine in comments, I changed while to if , for two reasons:

  • As it will only return a result, it does not need while ;
  • putting 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";

    }
    ?>
    
24.09.2015 / 00:56
4

Implement this way and do not forget to recover the error, there may be some exceptions and you are not recovering.

Try this:

$leitura = "SELECT * FROM php_teste"; <== seu select
$resultado =mysqli_query($leitura) or die (mysqli_error());
if(mysqli_num_rows($resultado) <=0){
    echo 'não tem nada';
} else {
    while($mostra = mysqli_fetch_assoc($query)){
        print_r($mostra);
    }
}
    
19.09.2015 / 16:07
1

Place:

$linha = $query->fetch_array(MYSQLI_ASSOC);
$variavel=$linha["NOME DA COLUNA DESEJADA"];
    
19.09.2015 / 18:31