I want to fetch multiple result sets from a stored procedure in laravel. Is there a way I can do this? Currently, I can get a single row's data using the below code:
$result = DB::statement('CALL user_login(' . $userId . ',"'
. $password . '",'
. '@success'.','
. '@first_Name'
);
$res = DB::select('select @success AS success, @first_Name AS firstName);
Here is my stored procedure:
DELIMITER //
DROP PROCEDURE IF EXISTS user_login//
create procedure user_login (IN userid VARCHAR(50),
IN password VARCHAR(50),
out success int,
OUT first_Name VARCHAR(255),
)
begin
declare count int(1);
set count =0;
select firstName, count(*)
into first_Name, count
from `tmc`.user where user_id = userid and pwd=password;
if count >0 then
set success =0;
else
set success=1;
end if;
end//
I am using the following code and it works flawlessly. Change it to suit your needs.
Example call:
The resulting call will be:
If there is only one resultset, it will be returned as is. If there are more, it will return an array of result sets. The key is using
$pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
. Without it, a horribleSQLSTATE[HY000]: General error: 2053
exception will be thrown.The try{} catch() block is used to eliminate the resultsets that cannot be fetched. Particularly, I have procedures that returns two resultsets, one as a result of an update (or other execute statements) and the last one as the real data. The exception thrown on
fetchAll()
with an execute query will bePDOException
.Warning: the function is not optimised. You can rewrite it with one single pass through the parameters.