note 87589 added to pdo.lastinsertid

From: Date: Thu, 11 Dec 2008 20:03:57 +0000
Subject: note 87589 added to pdo.lastinsertid
Groups: php.notes 
Request: Send a blank email to php-notes+get-148047@lists.php.net to get a copy of this message
Workaround for the fact that MSSQL does not provide lastInsertId() <?php $mixRc = false; try { // Issue a compound command, 2nd part outputs the inserted Id $strQuery = 'INSERT INTO t1 (f1,f2) VALUES(v1,v2); SELECT @@IDENTITY AS mixLastId'; // Yup, your eyes are ok, NOT exec but query!!! $objSth = $objDb->query($strQuery); $mixRc = (is_object($objSth) and $objSth->errorCode() == '00000'); } catch (PDOException $objException) { $pdoMsg = $objException->getMessage(); $pdoMsg = iconv("ISO-8859-1", "UTF-8", $pdoMsg); $strMessage = 'insertRecord: Failed ' . $strQuery . ', Error Message: ' . $pdoMsg; doLog(__FILE__, __LINE__, $strMessage); throw new core_exception_database($strMessage); } if ($mixRc === false) return false; // The compound command delivers a multi-rowset statement handle // Move past the first (invalid) rowset from the INSERT command $objSth->nextRowset(); // Pick up the first row of the rowset from "SELECT @@IDENTITY" $rowTd = $objSth->fetch(PDO::FETCH_NUM); if (!is_array($rowTd)) { doLog(__FILE__, __LINE__, 'insertRecord: $objSth->fetch() returns %s', gettype($rowTd)); return false; } $objSth->closeCursor(); $strLastRowId = $rowTd[0]; // An integer is returned as "nn,00" - catch and delete the ",00" $p = strpos($strLastRowId,','); if ($p !== false) $strLastRowId = substr($strLastRowId, 0, $p); // Remove all '.' $strLastRowId = str_replace('.', '', $strLastRowId); // A GUID, which contains no "," or ".", will be left unchanged return $strLastRowId; ?> ---- Server IP: 217.13.201.10 Probable Submitter: 92.198.39.50 ---- Manual Page -- http://www.php.net/manual/en/pdo.lastinsertid.php Edit -- https://master.php.net/note/edit/87589 Del: integrated -- https://master.php.net/note/delete/87589/integrated Del: useless -- https://master.php.net/note/delete/87589/useless Del: bad code -- https://master.php.net/note/delete/87589/bad+code Del: spam -- https://master.php.net/note/delete/87589/spam Del: non-english -- https://master.php.net/note/delete/87589/non-english Del: in docs -- https://master.php.net/note/delete/87589/in+docs Del: other reasons-- https://master.php.net/note/delete/87589 Reject -- https://master.php.net/note/reject/87589 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#148047) next »