Get last ID value and add +1 in SQL Database

Asked

Viewed 177 times

-2

I’m new to this language, I was previously using a auto_increment to save the ID sequentially in the bank, but found problems in other functions. My question is: How do I get the last "id" of the bank and add +1 - Follow what I was trying, but unsuccessfully:

<?php 

    include 'conecta_mysql.inc';

    $id1 = 'SELECT LAST(id) FROM t_saida';
    $id = $id1+1;
    $os = $_POST['os'];
    $data = $_POST['data'];
    $tech = $_POST['tech'];
    $descri = $_POST['descri'];
    $pag = $_POST['pag'];
    $valor = $_POST['valor'];

 $query = "INSERT INTO t_saida (id,data,os,tech,descri,pag,valor) VALUES ('$id','$data','$os','$tech','$descri','$pag','$valor')"; 


if (mysqli_query($link, $query)) {
      echo "Inserido com sucesso!";
      echo "<script>window.open ('','_self')</script>";
} else {
      echo "Erro: " . $sql . "<br>" . mysqli_error($link);
}
mysqli_close($link);


?>

Notice that I enter the data through a form, and try to increment the id with the variable $id1 and $id.

  • Instead of LAST, use MAX in SQL, but you need to submit this query to return the value.

  • Submit, you speak, before entering the form data?

  • Something like this: $id1 = 'SELECT max(id) FROM t_output'; mysqli_query($link, $id1); ?

1 answer

0

It could be something like:

"INSERT INTO t_saida (id,data,os,tech,descri,pag,valor) VALUES ((select coalesce(max(id),0)+1 from t_saida),'$data','$os','$tech','$descri','$pag','$valor')"; 

But the auto incremment is from the database, regardless of language.

  • That’s right, friend, but it caused this error: "You can’t specify target table 't_saida' for update in FROM clause"

  • This is on an Insert... not on an update...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.