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条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!