我正在尝试使用PDO调用SP(存储过程)。
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成功执行并将数据插入相关表格,并假设返回新插入的ID。但是当我打印结果时,我得到一个空数组。
有什么建议吗?
以下是我正在使用的SP:
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 ;
编辑:从不担心。
我认为通过使用$ result变量,我将能够获取OUT变量的值。但后来我发现我需要使用另一个SQL查询来获取那些输出变量。
$stmt = $conn->query("SELECT @user_id,@product_id");
答案 0 :(得分:1)
试试这个......
try
{
// Connecting using the PDO object.
$conn = new PDO("mysql:host=$host; dbname=$dbname", $user, $password);
$stmt = $conn->prepare('CALL sp_user(:demouser, :demoproduct, @user_id, @product_id)');
$demouser = "demouser";
$demoproduct = "demoproduct";
$stmt->bindParam(":demouser", $demouser, PDO::PARAM_STR, 255);
$stmt->bindParam(":demoproduct", $demoproduct, PDO::PARAM_STR, 255);
$stmt->execute();
$result = $conn->query("select @user_id, @product_id;")->fetchAll();
print_r($result);
foreach($result as $row)
{
echo $row["@user_id"];
echo $row["@product_id"];
}
}
// Catching it if something went wrong.
catch(PDOException $e)
{
echo "Error : ".$e->getMessage();
}
答案 1 :(得分:0)
您可以使用以下代码获取最后插入的ID:PDO::lastInsertId();
我认为您目前正在从fetchAll
返回数组,我认为其中不包含ID:http://php.net/manual/en/pdostatement.fetchall.php
答案 2 :(得分:0)
尝试这个
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`sp_user`$$
CREATE PROCEDURE `sp_user`(
IN user_name VARCHAR(255),
IN product_name VARCHAR(255)
)
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;
SELECT user_id, product_id;
END$$
DELIMITER ;
PHP中的
$result = $conn->query("CALL sp_user(demouser, demoproduct)")->fetchAll();
var_dump($result);