-1

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
m_id  KayitZaman       
16      1413130807000

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

andrew
  • 9,313
  • 7
  • 30
  • 61
traBolics
  • 89
  • 1
  • 3
  • 13
  • 2
    Why don't you retrieve the last inserted id via PDO (as described [here](http://stackoverflow.com/questions/5057954/get-last-insert-id-after-a-prepared-insert-with-pdo))? – kero Oct 12 '14 at 16:25

2 Answers2

1

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));
meda
  • 45,103
  • 14
  • 92
  • 122
  • Can you give me an example procedure for insert and return? – traBolics Oct 12 '14 at 22:24
  • @traBolics I expanded on my answer, I also answered an [older question](http://stackoverflow.com/questions/26208509/wamp-pdo-mysql-could-not-find-driver/26331128#26331128) – meda Oct 12 '14 at 23:38
0

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.

O. Jones
  • 103,626
  • 17
  • 118
  • 172