0
Hi. I’m having trouble getting the last registered ID. I’ve made a lot of attempts, but the $proximo_ID variable always returns me '0', or Empty. You could help me solve the problem?
if(isset($_REQUEST['btn-cadastro'])) {
try {
$wID = $_REQUEST['cadastro_ID'];
$DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
$DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $DB_con->prepare('SELECT ID FROM tbl_casualidade WHERE ID = :wID');
$stmt->execute(array('wID' => $wID));
$result = $stmt->fetchAll();
if (count($result)){
foreach($result as $row){
$proximo_ID = $DB_con->lastInsertId();
}
}
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$modelo = '<div id="link_'.$proximo_ID.'"></div>';
try {
$sql = "INSERT INTO tbl_casualidade (ID, nome, modelo) VALUES ('$ID', '".$nome."', '".$modelo."')";
$stmt = $DB_con->prepare($sql);
$stmt->execute();
echo "<div class='alert alert-success alert-dismissable' style='margin-top: 57px; margin-left: 45px; margin-bottom: -60px; margin-right: 15px;'>
<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>
<strong>PERFEITO!</strong> Página cadastrada com sucesso...
</div>";
}
catch(PDOException $e)
{
echo "<div class='alert alert-danger alert-dismissable' style='margin-top: 57px; margin-left: 45px; margin-bottom: -60px; margin-right: 15px;'>
<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>
<strong>FALHA!</strong> Por favor, tente enviar novamente...
</div><br />";
echo $sql . "<br>" . $e->getMessage();
}
$DB_con = null;
}
Are you trying to get the last id before inserting? There is no need for 2 Try {} where you are only doing one operation in the bd.
– Maurivan
Yes, that’s right. I need before inserting see which was the last ID and pass it to the variable $proximoID
– Fabio
So just use
select max(id) + 1 as id from tbl_casualidade
If you have not entered, there is no way to get the last inserted id.– Maurivan
But there is no way before I enter, I check what is the last id that is registered in the bank and add +1?
– Fabio
I’ve posted:
select max(id) + 1 as id from tbl_casualidade
$proximo_ID = $result[0]['id']
– Maurivan
I did exactly as you said, but the value comes empty.
– Fabio
If it is the first record returns empty anyway! Fixing:
select ifnull(max(id),0) + 1 as id from tbl_casualidade
– Maurivan
Now it’s not empty, but there’s always 1.
– Fabio
Field id is not auto_increment | Identity ? Another question: where does $ID come from
$sql = "INSERT INTO tbl_casualidade (ID, nome, modelo) VALUES ('$ID', '".$nome."', '".$modelo."')";
If auto_increment replace with$sql = "INSERT INTO tbl_casualidade (nome, modelo) VALUES ({$nome}, {$modelo})";
– Maurivan
It worked. I was passing the $_REQUEST parameter with the wrong name. Thank you very much Maurivan.
– Fabio
Aiello, for nothing! Arrange.
– Maurivan
If you want to add one more, do it
$variavel++
with the result received– Danilo Araujo