I am trying to call SP(stored procedure) using PDO.
try {
// Connecting using the PDO object.
$conn = new PDO("mysql:host=$host; dbname=$dbname", $user, $password);
$stmt = $conn->prepare('CALL sp_user(?,?,@user_id,@product_id)');
$stmt->execute(array("demouser", "demoproduct"));
$result = $stmt->fetchAll();
print_r($result);
}
// Catching it if something went wrong.
catch(PDOException $e) {
echo "Error : ".$e->getMessage();
}
SP is executed successfully and inserted data into relevant tables and suppose to return the new inserted id. But when I print the result, I get an empty array.
Any suggestion?
Below is the SP I am using:
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`sp_user`$$
CREATE PROCEDURE `sp_user`(
IN user_name VARCHAR(255),
IN product_name VARCHAR(255),
OUT user_id INT(11),
OUT product_id INT(11)
)
BEGIN
START TRANSACTION;
INSERT INTO `user` (`name`) VALUES(user_name);
SET user_id := LAST_INSERT_ID();
INSERT INTO `product` (`name`) VALUES(product_name);
SET product_id := LAST_INSERT_ID();
INSERT INTO `map_user_product` (`user_id`,`product_id`) VALUES(user_id,product_id);
commit;
END$$
DELIMITER ;
Edit: NEVER MIND.
I thought by using $result variable i will be able to fetch the OUT variable's value. But later i found that i needed to use another SQL query to fetch those out variables.
$stmt = $conn->query("SELECT @user_id,@product_id");