last insert id in pdo

2019-09-03 15:49发布

问题:

I have a form with only one input. When I click the button, an AJAX request is made and the data is sent to the response.php, which uses the pdo library to insert the data to db. Here it is okay, but in the page, there is a success function which loads the data into the form - when the ajax request completes, the result is blank...I need to refresh(F5) the page to see the data .. Here is this code:

<?php
include_once("config.php");
if (!empty($_POST)) {
        try{
    $statement = $conn->prepare("INSERT INTO DIAGNOSTICO (id_paciente, id_doctor, hconsulta) VALUES (?, ?, ?)");

    if ($statement->execute(array($_POST['id_paciente'], $_POST['id_doctor'], $_POST['hconsulta'])));
        $dbSuccess = true;

} catch (Exception $e) {
    $return['databaseException'] = $e->getMessage();
}
 {
echo $conn->lastInsertId(); 
echo '<li id="item_'.$row["id_diagnostico"].'">';
echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$row["id_diagnostico"].'">';
echo '<img src="../images/icon_del.gif" border="0" />';
echo '</a></div>'; echo ' Fecha de consulta : ';echo $row["f_diagnostico"]; echo ' <br><br> ';
echo $row["hconsulta"].'</li>';
}
   $dbh = null;  
}
?>

It is working, but when in the page, the result returns from the ajax request and shows the id but not the data...I need the data result...can you help me?

best regards!

回答1:

After using the lastinsertid you have to select data by using

$sth = $dbh->prepare("SELECT * FROM DIAGNOSTICO WHERE id_diagnostico= ".$conn->lastInsertId());
$sth->execute();

$row = $sth->fetch(PDO::FETCH_ASSOC);
echo '<li id="item_'.$row["id_diagnostico"].'">';
echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$row["id_diagnostico"].'">';
echo '<img src="../images/icon_del.gif" border="0" />';
echo '</a></div>'; echo ' Fecha de consulta : ';echo $row["f_diagnostico"]; echo ' <br><br> ';
echo $row["hconsulta"].'</li>';

Read http://php.net/manual/en/pdostatement.fetch.php