问题
My problem is this: I Created a store procedure from php to mysql. Now before someone says something about that practice, The procedure works fine. The problem is this, when I call the procedure from php and I KNOW that a record has been entered, mysql_insert_id(), returns 0... Any ideas why?
Oh, and yes, my id field is AUTO_INCREMENT and PRIMARY KEY
p.s If there's an easy way to format my code in here, pls tell me. I put pre in html, but it doesn't seem to work very well.
Ty in advance.
$PROCEDURE_INSERT_UPDATE_BOARD =
"
CREATE PROCEDURE InsertUpdateBoard(IN `pNewBoardUUID` CHAR(36),
IN `pOldBoardUUID` CHAR(36),
IN `pSimName` VARCHAR(40),
IN `pOwnerName` VARCHAR(64),
IN `pOwnerUUID` CHAR(36),
IN `pLandmark` VARCHAR(80),
IN `pVersion` VARCHAR(10),
IN `pManagerUUID` CHAR(36),
IN `pBoardURL` CHAR(80),
IN `pPassword` CHAR(8))
BEGIN
CALL InsertUpdateSims(`pSimName`);
CALL InsertUpdateAvatars(`pOwnerName`, `pOwnerUUID`);
INSERT INTO boards(`boardUUID`, `simId`, `ownerId`, `landmark`,
`version`, `managerId`, `boardURL`, `password`)
VALUES(`pOldBoardUUID`,
(SELECT rS.id FROM 2starsglobal.sims AS rS
WHERE rS.name=`pSimName`),
(SELECT rA.id FROM 2starsglobal.avatars AS rA
WHERE rA.UUID = `pOwnerUUID`),
`pLandmark`, `pVersion`,
(SELECT rA2.id FROM 2starsglobal.avatars AS rA2
WHERE rA2.UUID = `pManagerUUID`),
`pBoardURL`,
`pPassword`)
ON DUPLICATE KEY UPDATE `boardUUID`=`pNewBoardUUID`,
`landmark`=`pLandmark`, `version`=`pVersion`,
`boardURL`=`pBoardURL`;
END
";
And the Php code
function InsertUpdateBoard($boardNewUUID, $boardOldUUID, $simName,
$ownerName, $ownerUUID, $boardLandmark,
$versionNumber, $managerUUID, $boardURL)
{
$password = generatePassword(8);
$query = "CALL InsertUpdateBoard('$boardNewUUID', '$boardOldUUID', '$simName',
'$ownerName', '$ownerUUID', '$boardLandmark',
'$versionNumber', '$managerUUID', '$boardURL',
'$password')";
mysql_query($query) or die("ERROR:QUERY_FAILED " . mysql_error());
if(mysql_affected_rows() > 0)
{
if(mysql_insert_id() > 0)
{
echo "SUCCESS,$password";
}
else
{
echo "SUCCESS";
}
}
else
{
echo 'FAILED:BOARD_REGISTRATION_UPDATE';
}
}
回答1:
Ten seconds with google found this page
Note that if you Call a MySQL stored procedure to insert a new record and then reference $db->insert_id; you will get 0 back, not the last inserted ID.
It is therefore necessary to add a line to your MySQL Stored Procedure such as
select last_insert_id() as intRecordKey;
after the insert so that the query will return the new key value.
来源:https://stackoverflow.com/questions/12759023/stored-procedures-and-mysql-insert-id-issue