0

my pdo last insert id returns 0 here is the code

  $bdd->beginTransaction();
$requete = $bdd->prepare('INSERT INTO reservation (code_salle,date_res,code_cr,code_profe)
 VALUE (:code_salle,:date_res,:code_cr,:code_profe)');
             $requete->execute(array(
                 'code_salle'=>$Salle,
                 'date_res'=>$date,
                 'code_cr'=>$heure,
                 'code_profe'=>$prof,   
             ));
            
  $last_id = $bdd->lastInsertId();
  echo "New record created successfully. Last inserted ID is: " .$last_id;


  $bdd->commit();

and here is my connexion

try
{
     $bdd = new PDO('mysql:host=localhost;dbname=ebooking;charset=utf8', 'root', '');
     $bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
     
}
catch(Exception $e)
{
        die('Erreur : '.$e->getMessage());
} 

tried with the

 $bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

ALSO didn't work and also the

var_dump($bdd->lastInsertId());

didn't work ALL I'M GETTING IS C:\wamp64\www\E-booking\try.php:76:string '0' (length=1)

or

New record created successfully. Last inserted ID is: 0

in the data base it's an" Id Primaire AUTO_INCREMENT" i think i've tried every solution i can find here on stackoverflow and yet nothing is working what am I doing wrong ?

  • 2
    Try removing the line `$bdd->exec($requete);` as the `execute` on the previous line should have already inserted the row. – Nigel Ren May 07 '22 at 12:04
  • @NigelRen when i remove it the " $last_id = $bdd->lastInsertId(); echo "New record created successfully. Last inserted ID is: " .$last_id;" doesn't even echo – rana oumnia May 07 '22 at 12:33
  • Is the data going into the DB OK? – waterloomatt May 07 '22 at 13:07
  • @waterloomatt yes it is and the id is increasing just fine i'm stuck on this for a day now and can't move until i get this id – rana oumnia May 07 '22 at 13:11
  • Can you confirm the code you showed us is exact? If the `commit` is before the lastInsertId you will get `0`. See here on line 20, https://extendsclass.com/php-bin/e132c87. Try moving that commit below the lastInsertId. Try removing the transaction to see if that fixes things. Nigels comment is right. You should only execute once. – waterloomatt May 07 '22 at 13:12
  • the commit is below lastInsertId as showen in the code and even when i excuted once still returning 0 @waterloomatt – rana oumnia May 07 '22 at 13:15
  • Can you edit and update your question's code with the latest changes since you removed `$bdd->exec($requete);`, pls? – waterloomatt May 07 '22 at 13:26
  • done well practically nothing changed the outcome is still the same : New record created successfully. Last inserted ID is: 0 @waterloomatt – rana oumnia May 07 '22 at 13:42
  • 1
    What is the reservation table definition? – Paul T. May 08 '22 at 01:43
  • @PaulT. i figured what's wrong with my code the probleme is in $Salle it's detected as Null – rana oumnia May 09 '22 at 10:46

0 Answers0