PDO: What is the best method to get the result after inserting the data into the database

advertisements

I´m very new to PDO. I just wonder what´s the best way to get the result when the data insert to the database comletely. I´m looking around in googl. seems like it´s flexible. That makes me wonder what is correct and what is incorrrect way.

Let see example:

$sql = $conn->prepare("INSERT INTO tb_user(user_name, user_email) VALUES(:user_name,:user_email);
$sql->execute(array(':user_name'=>$user_name, ':user_email'=>$user_email));
$affected_rows = $sql->rowCount();

From this script I want to get result if the data is finish to be insert in database. If it done-->I will echo it like "complete" and send it back to ajax or etc...

I have tried :

if($affected_rows){
echo"YEZZ!! complete";
}

And

$all = $slq->fetchAll();
if(count($all)) {
echo"YEZZ!! complete";
}

And

if ($sql->execute){
echo"YEZZ!! complete";
//this one i know it will double insert data to database because I called it twice//
But I still want to know when can I use this method

And maybe more ways out there which make me crazy and want to know what is the best way to get result if the thing is done: AFter insert, after delete, after update these 3 statements is the most important to know each.

Any suggestions could be wonderful ! } }


you could do:

$id = $conn->lastInsertId('IDCOLUMN');

and then execute a query and search for the id

$stmt = $conn->prepare("SELECT * FROM tb_user WHERE IDCOLUMN = :id");
$stmt->execute(array("id", $id);
if($stmt->rowCount() > 0) {
   $result = $stmt->fetch(PDO::FETCH_ASSOC);
}

the result variable will contain your last inserted record