Pick up a record as soon as it is saved in the bank

0

I'm writing a record to my database like this:

$tipo = $_POST['tipo'];
$data = $_POST['data'];

include 'conexao.php';

$result = mysqli_query($con, "insert into sessoes
                              (tipo, data) values
                              ('".$tipo."', '".$data."')");
//o registro grava corretamente

if (!$result) { //vejo se tem algum erro
    throw new Exception(mysqli_error($con)."insert into sessoes
                                            (tipo, data) values
                                            ('".$tipo."', '".$data."')");
}else{
  mysqli_commit($con); //dou um commit no banco de dados
  $result = mysqli_query($con, "select * sessoes order by id desc");
  //NA LINHA ACIMA, TENTO PEGAR O ÚLTIMO REGISTRO SALVO, MAS O MESMO NÃO É RETORNADO, MESMO QUE EU VEJO NO BANCO E ELE ESTÁ LÁ
  $linha = mysqli_fetch_assoc($result); //linh fica null
  $idSessao = $linha['id']; //idSessao fica null
  //header('location:participaram.php?idSessao='.$idSessao);
}

mysqli_close($con);

As you can see in the code, it writes the data to the database, but does not return the saved record. What could be wrong?

The sessoes table:

id int
data date
tipo int
    
asked by anonymous 19.02.2018 / 18:51

1 answer

1

The error

The error is in query . FROM was missing. The correct one is: select * FROM sessoes order by id desc

  

I'll explain below why you should not use this way to capture the last ID.

Solutions

Use mysqli_insert_id to return the last ID entered.

  $idSessao = mysqli_insert_id($con);
  header('location:participaram.php?idSessao='.$idSessao);

In addition, you can also use query :

SELECT LAST_INSERT_ID() AS lastId;

It's the same, but a bit more code (due to PHP).

Observations

There is a problem using select * sessoes order by id desc . When it comes to performance, this code is not recommended. Maybe in the beginning and in localhost , it seems interesting, the problem is that in a production server with thousands of access this becomes a nightmare, especially when you have a lot of data inserted.

Before using a MySQL code, use EXPLAIN up front, so you can see how your query behaves when executed.

Ex: EXPLAIN SELECT * FROM sessoes ORDER BY id desc

    
19.02.2018 / 19:23