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

报告相同问题?

悬赏问题

  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持