dopcpc9207 2014-10-12 16:23
浏览 49
已采纳

Php Pdo - 选择最后插入

i have a 'insert into' and 'select' querys together in one query.

$_SESSION['LoginUID']=1;
$Mesaj='ffdd';
$Ek=12;
$cid=112;
$Kaydet=$db->query("
               Insert Into Reply (Kimden,Mesaj,Ek,cid) 
               Values (".$_SESSION['LoginUID'].",'$Mesaj',$Ek,$cid);
               select r_id,KayitZaman from Reply 
               where r_id=LAST_INSERT_ID();")
            ->fetch(PDO::FETCH_ASSOC);

But i cant select last inserted row. It must return like this
<kbd>m_id  </kbd><kbd>KayitZaman       </kbd>
<kbd>16      </kbd><kbd>1413130807000</kbd>

How can i do that in one query? Or other way.

  • 写回答

2条回答 默认 最新

  • dowjgrm6787 2014-10-12 16:59
    关注

    You cannot run two queries at the same time, only one at the time

    After the insert, run the select:

    $stmt = $db->query('select r_id,KayitZaman from Reply where r_id=LAST_INSERT_ID()');
    

    or you can use the built in function to pass the last inserted Id

    $stmt = $db->prepare('select r_id,KayitZaman from Reply where r_id= ?');
    $stmt->execute(array($db->lastInsertId()));
    

    If you want to do the whole thing at once then create a stored procedure.


    EDIT:

    DELIMITER //
     CREATE PROCEDURE sp_insert_get_reply(IN `p_Kimden`, 
                                          IN `p_Mesaj`, 
                                          IN `p_Ek`, 
                                          IN `p_cid`)
       BEGIN
       INSERT INTO `Reply` (`Kimden`, `Mesaj`, `Ek`, `cid`) 
       VALUES (p_Kimden, p_Mesaj, p_Ek, p_cid);
    
       SELECT `r_id`, `KayitZaman` 
       FROM Reply WHERE r_id=LAST_INSERT_ID()
       END //
     DELIMITER ;
    

    then call the function from PDO:

    $stmt = $db->prepare('CALL sp_insert_get_reply(?, ?, ?, ?)');
    $stmt->execute(($_SESSION['LoginUID'], $Mesaj, $Ek, $cid));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题