How do i know if successfully inserted

Hi, I just want to ask some help on this PDO, i am inserting record in my table using PDO.What i want is to echo if i have successfully inserted or echo Failed.

Insert.php


       $fname     = $_POST['fname'];
       $lname     = $_POST['lname'];
       $age        = $_POST['age'];


       $query = $db->prepare('INSERT into test(firstname,lastname,age) values(?,?,?)');
       $query ->execute(array($fname,$lname,$age));
       $passed = $query->execute();

        if($passed)
           echo  "Successfully Inserted";
        else
           echo  "Failed in insert";





I tried to change the variable $age to $ages so that it will print Failed in insert,but it did not perform the else statment,can you help me please how can i determine if i have succesfully inserted or Failed in insert.

Thank you in advance.

Did it put anything in your database?

Hi cups, No data is inserted because it has an error of variable $ages it should be $age…but what i want is to execute else statement if there is an error…i also tried to insert properly but what happened is that it will insert repeatedly i mean 2 rows will be inserted with the same data…I read in the php manual that PDO::execute() will return values true and false. I think the execute will not return anything…I am confuse on this.can you help me please.

Thank you in advance.

       $query ->execute(array($fname,$lname,$age)); 
       $passed = $query->execute(); 

        if($passed) 
           echo  "Successfully Inserted"; 
        else 
           echo  "Failed in insert";  

Yeah, I see, you are executing twice …

Try:

       $query ->execute(array($fname,$lname,$age)); 
       
// do this to see what query is returning exactly
var_dump($query); 

        if($query) 
           echo  "Successfully Inserted"; 
        else 
           echo  "Failed in insert";  

Hi cups,

Something like this

object(PDOStatement)[2]
public ‘queryString’ => string ‘INSERT into test(firstname,lastname,age) values(?,?,?)’ (length=89)

Sorry, I see what you mean now, try this answer.