How do I take the auto increment ID using Mysql and PHP and use it later?

Asked

Viewed 1,342 times

1

I am creating an API in PHP and insert. I need to take the ID created in this INSERT and use later. What I find material, it seems not recommended. Any solution? Thank you.

My PHP:

    <?php

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

    //formulário

    $data = file_get_contents("php://input");
    $objData = json_decode($data);

    // TRANSFORMA OS DADOS

    $nome = $_GET['nome'];
    $endereco = $_GET['endereco'];
    $numero = $_GET['numero'];
 //   $complemento = $_GET['complemento'];
    $bairro = $_GET['bairro'];
    $cidade = $_GET['cidade'];
    $estado = $_GET['estado'];
    $cod_cliente = $_GET['cod_cliente'];
    $outro_endereco_cod = $_GET['outro_endereco_cod'];
    $forma_pagamento = $_GET['forma_pagamento'];
    $troco = $_GET['troco'];
    $frete = $_GET['frete'];
    $valor_pedido = $_GET['valor_pedido'];
    $cod_fornecedor = $_GET['cod_fornecedor'];
    $total_pedido = $_GET['total_pedido'];

     // INSERE OS DADOS
    $db = new PDO("DADOS DA MINHA CONEXAO");


    if($db){

        $sql = "INSERT INTO dados_pedido (nome, endereco, numero, bairro, cidade, estado, cod_cliente, outro_endereco_cod, forma_pagamento, troco, frete, valor_pedido, cod_fornecedor, total_pedido) VALUES ('$nome', '$endereco', '$numero', '$bairro', '$cidade', '$estado', '$cod_cliente', '$outro_endereco_cod', '$forma_pagamento', '$troco', '$frete', '$valor_pedido', '$cod_fornecedor', '$total_pedido')";


        $query = $db->prepare($sql); 

        $query ->execute();    





        echo json_encode(array('message'=> ' Os dados foram inseridos com sucesso. Obrigado e bem vindo!' ));
    }else{
        echo json_decode(array('message'=> ' Não foi possivel iserir os dados! Tente novamente mais tarde!' ));
    };

?>
  • 1

    Have you tried $id = $db->lastInsertId();?

  • It worked! Thanks @Andersoncarloswoss

  • I will put as an answer so I can signal as answered

  • Was any of the answer helpful? Don’t forget to choose one and mark it so it can be used if someone has a similar question!

1 answer

3


The PDO class, in PHP 5.1.0+, has a method called lastInsertID, according to official documentation.

PDO::lastInsertIdReturns the ID of the last inserted Row or Sequence value

So, after running your query, just take back the value of $db->lastInsertId() to obtain the id of the new record.

$db = new PDO(...);
$sql = "INSERT INTO ...";
$query = $db->prepare($sql);
$query->execute();
$id = $db->lastInsertId();

echo "Último id inserido: " . $id;

The code snippet above would be a simple example of how to use the latter id inserted.

Note: This method may not Return a Meaningful or consistent result Across Different PDO drivers, because the underlying database may not Even support the notion of auto-increment Fields or sequences.

  • 1

    A tip, before answering, check in the search if there is no answer to the question and then mark the question as duplicate, example search http://answall.com/search?tab=votes&q=lastInsertId (discussion at goal: http://meta.pt.stackoverflow.com/q/5719/3635)

Browser other questions tagged

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