2014-10-12 16:23
浏览 48

Php Pdo - 选择最后插入

i have a 'insert into' and 'select' querys together in one 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();")

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

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= ?');

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


     CREATE PROCEDURE sp_insert_get_reply(IN `p_Kimden`, 
                                          IN `p_Mesaj`, 
                                          IN `p_Ek`, 
                                          IN `p_cid`)
       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 //

    then call the function from PDO:

    $stmt = $db->prepare('CALL sp_insert_get_reply(?, ?, ?, ?)');
    $stmt->execute(($_SESSION['LoginUID'], $Mesaj, $Ek, $cid));
    打赏 评论
  • douzachan4578 2014-10-12 16:59

    You should try issuing your insert in a PDO exec() call, and following it up with your select in the query call. You can still use LAST_INSERT_ID() in your select query and retain data integrity.

    If, for some reason, you must do the two statements in a single request from your program, you can use the multiple-statement feature of mysqli or you can write a stored procedure.

    打赏 评论

相关推荐 更多相似问题