我在mysql中将存储过程存储为:sp_get_country_by_id
BEGIN
SELECT id, name FROM countries WHERE id = country_id;
END
我正在使用PDO对其进行如下调用:
$stmt1 = $dbh->prepare("CALL sp_get_country_by_id(?)");
$stmt1->bindParam(1, $id);
$id = 102;
$stmt1->execute();
print_r($stmt1->fetch(PDO::FETCH_ASSOC));
$id = 103;
$stmt1->execute();
print_r($stmt1->fetch(PDO::FETCH_ASSOC));
它返回结果如下:
Array
(
[id] => 102
[name] => Indonesia
)
预计将返回两个数组,如下所示:
Array ( [id] => 102 [name]=>Indonesia)
Array ( [id] => 103 [name]=>Iran)
根据评论,我在这里添加存储过程:
CREATE PROCEDURE `sp_get_country_by_id`(IN `country_id` INT)
BEGIN
SELECT id, name FROM countries WHERE id = country_id;
END
我正在关注这个例子。用INSERT进行示例解释,而我正在尝试SELECT
http://php.net/manual/en/pdo.prepared-statements.php#example-1028
答案 0 :(得分:0)
我很惊讶它返回了您所显示的内容。您的$id
变量可能在->prepare
指令之前包含102
我假设您的SP在名为country_id
的变量中输入了国家ID,但没有显示
要使其正常工作,您应该准备,绑定并执行2次:
$stmt1 = $dbh->prepare("CALL sp_get_country_by_id(?)");
$id = 102;
$stmt1->bindParam(1, $id);
$stmt1->execute();
print_r($stmt1->fetch(PDO::FETCH_ASSOC));
$stmt1 = $dbh->prepare("CALL sp_get_country_by_id(?)");
$id = 103;
$stmt1->bindParam(1, $id);
$stmt1->execute();
print_r($stmt1->fetch(PDO::FETCH_ASSOC));
但是如果必须多次执行此操作,最好为其创建一个函数:
print_country_data_array(102);
print_country_data_array(103);
function print_country_data_array($countryID){
global $dbh;
$stmt1 = $dbh->prepare("CALL sp_get_country_by_id(?)");
$stmt1->bindParam(1, $countryID);
$stmt1->execute();
print_r($stmt1->fetch(PDO::FETCH_ASSOC));
}