-3

i'm facing this Problem when i try to select the last inserted id from Mysql table, i get the value = bool(true) instead of the values.

What i'm trying to do:

if (isset($_POST['submit'])){
                if (isset($_POST['paName']) && isset($_POST['paEmail']) && isset($_POST['paTel']) && isset($_POST['aName']) && isset($_POST['Artnum'])){
                    
                    if (!empty($_POST['paName']) && !empty($_POST['paEmail']) && !empty($_POST['paTel']) && !empty($_POST['aName']) && !empty($_POST['Artnum'])){
                        
                         $paName = $_POST['paName'];
                         $paEmail = $_POST['paEmail'];
                         $paTel = $_POST['paTel'];
                         $aName = $_POST['aName'];
                         $Artnum = $_POST['Artnum'];
                      
                        $query = "INSERT INTO crud (paName,paEmail,paTel,aName,Artnum) VALUES ('$paName','$paEmail','$paTel','$aName','$Artnum')";
                       if ($sql = $this->conn->exec($query)){
                           $id = $this->conn->lastInsertId();
                           $query = "SELECT * FROM crud WHERE id = '".$id."'";
                           $stmt=$this->conn->prepare($query);
                           $stmt->execute();
                           var_dump($stmt->execute());die();
}

but if i do the same without conditions, i get all values from the table , so that's mean my condition is wrong.

can you tell me please what i'm doing wrong ?

Max
  • 41
  • 6

1 Answers1

3

It seems like you are missing $this->conn->prepare() in first query. You can try this example :

lastInsertId() only work after the INSERT query.

Correct:

$stmt = $this->conn->prepare("INSERT INTO crud (paName,paEmail,paTel,aName,Artnum) 
                              VALUES(?,?,?,?,?);");
$sonuc = $stmt->execute([$paName,$paEmail,$paTel,$aName,$Artnum]);
$LAST_ID = $this->conn->lastInsertId();

Incorrect:

$stmt = "INSERT INTO crud (paName,paEmail,paTel,aName,Artnum) VALUES ('$paName','$paEmail','$paTel','$aName','$Artnum')";
$sonuc = $this->conn->execute($stmt);
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
Bhavin Solanki
  • 4,740
  • 3
  • 26
  • 46