Get the last insert id ready

Asked

Viewed 44 times

-1

How do I get the last one ID created by insert?

$rs = $mysqli->prepare("INSERT INTO tabela (campo1, campo2, campo3) VALUES (?, ?, ?) ");

    $rs->bind_param('sss',
        $_POST['campo1'],
        $_POST['campo2'],
        $_POST['campo3']
        );

    $rs->execute();


    if ($rs->errno) {
        echo 'Erro: ', $rs->error;
    } else {
        echo "<script>window.location='PAGINA.php'</script>";
    }

Just use $ultimoId= $rs->insert_id;?

Then I can do it like this?

$rs->execute();
$ultimoId = $rs->insert_id;

    if ($rs->errno) {
        echo 'Erro: ', $rs->error;
    } else {
        echo "<script>window.location='PAGINA.php?id=$ultimoId'</script>";
    }
  • the $rs variable is your connection object? post your complete code so that we can understand right what are the variables

  • https://answall.com/questions/127456/forma-otimizada-recuperar-ultimo-id-mysql

  • @Julyanofelipe, $mysqli is the variable that has the database data. $rs is what receives the Insert and executes.

  • @James then what you’re looking for would be $conn->insert_id;

  • just use $mysql->insert_id

1 answer

-3

You can use the method:

$mysqli->lastInsertId()

Returns the ID of the last inserted row

  • 1

    Is there such a method at Mysqli? This is not a PDO thing?

Browser other questions tagged

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