doujiao4710 2013-08-10 09:45
浏览 98
已采纳

PDO:将数据插入数据库后得到结果的最佳方法是什么

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 ! } }

  • 写回答

2条回答 默认 最新

  • doumaqing6652 2013-08-10 10:57
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥18 深度学习tensorflow1,ssdv1,coco数据集训练一个模型
  • ¥100 关于注册表摄像头和麦克风的问题
  • ¥30 代码本地运行正常,但是TOMCAT部署时闪退
  • ¥15 关于#python#的问题
  • ¥15 主机可以ping通路由器但是连不上网怎么办
  • ¥15 数据库一张以时间排好序的表中,找出多次相邻的那些行
  • ¥50 关于DynamoRIO处理多线程程序时候的问题
  • ¥15 kubeadm部署k8s出错
  • ¥15 Abaqus打不开cae文件怎么办?
  • ¥15 小程序准备上线,软件开发公司需要提供哪些资料给甲方