Get the ID of the last line entered in the database

3

I'm doing a project that is in the following form:

First the person will upload the photo of her in the bd (Table: registered, field: photo) But in this table there are other fields, so I created a form that will change the last line and add the other fields (name, phone, email, etc.) while holding the photo.

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

I need the ID to be the last one I recorded the photo, but I do not know how to get it.

To better interpret my question :

Thisisthetable,andthefieldsofitMysql.Ialreadyrecordedthephotoasyoucansee.NowontheformIwanttogiveanUPDATEtoappendtheremaininginformationonthatlinethere(id=20)eg.

IMAGEINSERTCODE:

functionsaveimagem($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";
        }
    }
    
asked by anonymous 01.10.2015 / 01:31

1 answer

3

Friend there is a function called mysqli_insert_id() , it captures the id automatically generated in the last query where ÌNSERT or UPDATE was used.

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);
}

MySQL Insert ID - PHP.net

    
01.10.2015 / 01:47