Grab the ID of the last row inserted in the database

Asked

Viewed 1,161 times

3

I am doing a project that is in the following form:

First the person will upload her photo in the comic (Table: registered, field: photo) However this table has other fields, for this I created a form that will change the last line registered and add the other fields (name, phone, email etc) keeping the photo.

The problem is: UPDATE cadastro SET nome = $nome WHERE id = **PROBLEMA**;

I need the ID to be the last one that recorded the photo, but I don’t know how to get it.

To better interpret my doubt:

inserir a descrição da imagem aqui

This is the table, and its Mysql fields. I’ve already saved the photo as you can see. Now in the form I want to give an UPDATE to add the remaining information on that line there (id = 20).

IMAGE INSERT CODE:

function saveimagem($name, $image)
    {

        $host = "localhost";
        $user = "root";
        $pass = "";
        $conexao = mysqli_connect($host, $user, $pass) or die (mysql_error());
        mysqli_select_db($conexao, "teste");
        $sql = "insert into cadastro (foto)  values ('$image')";
        if($sql){
        print "ID: ". mysqli_insert_id($conexao);
        }
        $result = mysqli_query($conexao, $sql);
        if($result)
        {
            echo "<br/>Foi feito o upload";
        }else
        {
            echo "<br/>Não foi feito o upload";
        }
    }
  • 1

    What api is using to connect to the database?

  • @No, I’m doing everything

  • If you have any code ask the question :)

  • Just play the mysqli_insert_id() within the if($result)

  • Uffa. worked very well thanks. Do I need to do something now? Close the question?

  • Mark August response as accepted, How and why to accept an answer?

Show 1 more comment

1 answer

3


Friend there is a function called mysqli_insert_id(), she captures the id automatically generated in the last query in which the ÌNSERT or UPDATE.

Using the Oriented style:

$conexao = new mysqli("localhost", "usuario", "senha", "banco");
$stmt = $conexao->query("INSERT INTO tabela (campo1, campo2) VALUES (1, 'Nome')");
if($stmt){
print "ID: ". $conexao->insert_id;
}

Using the Procedural style:

$conexao = mysqli_connect("localhost", "usuario", "senha", "banco");
$stmt = mysqli_query($conexao, "INSERT INTO tabela (campo1, campo2) VALUES (1, 'Nome')");
if($stmt){
print "ID: ". mysqli_insert_id($conexao);
}

Mysqli Insert ID - PHP.net

  • 1

    Thanks man, on top of what you put I managed to do :DD

  • 1

    Just imagine... we’re here....

Browser other questions tagged

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