DELIMITER $$
USE `ejemplo`$$
DROP PROCEDURE IF EXISTS `insert_sp`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `insert_sp`(
IN ID VARCHAR(8),
IN Nombre VARCHAR(50),
OUT msg VARCHAR(50)
)
BEGIN
INSERT INTO empleado_php VALUES (ID, Nombre);
SELECT "Todo bien" INTO msg;
END$$
DELIMITER ;
并通过mysqli调用此方法,如果我使用下面的代码
,则Everythings工作正常if (!$mysqli->query("SET @msg = ''") ||
!$mysqli->query("CALL insert_sp('" . $id . "', '" . $nombre . "', @msg)"))
echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
if (!($res = $mysqli->query("SELECT @msg as _p_out")))
echo "Fetch failed: (" . $mysqli->errno . ") " . $mysqli->error;
并显示输出值:
$row = $res->fetch_assoc();
echo $row['_p_out'];
我的问题是:如果我必须使用准备好的语句,我想如何编码?你能不能给我一个例子......这是我到目前为止所做的但是不起作用
if (!$mysqli->prepare("SET @msg = ''") ||
!$mysqli->prepare("CALL insert_sp(?,?,@msg)"))
echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
if (!($res = $mysqli->prepare("SELECT @msg as _p_out")))
echo "Fetch failed: (" . $mysqli->errno . ") " . $mysqli->error;
if(!$mysqli->bind_param("ss", $id, $nombre)){
echo "Error en bind-param ingresar_sp.php " .$mysqli->connect_error;
}
$mysqli->execute();
$row = $res->fetch_assoc();
echo $row['_p_out'];
顺便说一句......我需要通过echo显示输出值。
提前致谢。
答案 0 :(得分:0)
非常简单,PHP官方网站评论说你必须使用会话变量(MySQL会话,而不是PHP),因此,我的问题的答案如下所示:
// bind the value of the first IN parameter to the session variable @id
$stmt = $mysqli->prepare("SET @id = ?");
$stmt->bind_param('s', $id);
$stmt->execute();
// bind the value of the second IN parameter to the session variable @nombre
$stmt = $mysqli->prepare("SET @nombre = ?");
$stmt->bind_param('s', $nombre);
$stmt->execute();
//bind the value of the OUT parameter
$stmt = $mysqli->prepare("SET @msg = ''");
$stmt->execute();
// execute the stored Procedure
$result = $mysqli->query('call insert_sp(@id, @nombre, @msg)');
// getting the value of the OUT parameter
$r = $mysqli->query('SELECT @msg as _p_out');
$row = $r->fetch_assoc();
echo $row['_p_out'];