Ir al contenido principal

Using MySQL Stored Procedure IN/OUT and Recordset w/ PHP

Note: The code below will not work on all environments. I’m using php 5.2.6 with mysql driver 5.0.18.

In a previous post:
http://www.joeyrivera.com/2009/using-mysql-stored-procedures-with-php-mysqlmysqlipdo/

I explained how to use MySQL stored procedures with different db adapters such as mysql, mysqli, and pdo in PHP. In those examples, I demonstrated calling a sp with in/out variables and calling a stored procedure that returns a recordset. One of the comments I received was a person asking how to call a stored procedure that uses in/out parameters as well as returns a recordset. It’s not much different and here’s how.

The trick is to combine both methods in one. Here’s an example of what the stored procedure looks like:

DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`get_users` $$
CREATE PROCEDURE `get_users`(
IN firstName VARCHAR(100),
OUT totalUsers INT
)
BEGIN
SELECT COUNT(*)
INTO totalUsers
FROM users
WHERE first_name = firstName;
SELECT *
FROM users
WHERE first_name = firstName;
END $$
DELIMITER ;

Notice there are two statements in the body of this stored procedure. The first select count(*) statement counts the total number of people who’s first name is equal to the in variable firstName. Once it’s gets the count, it sets the out variable totalUsers to that value.

The next statement is a simple select. This will select all fields for users who’s first name is equal to the in variable firstName and return the recordset. So by calling this stored procedure and passing in two parameters (first name, total), a recordset will be returned and an out variable will be set – that can then be queried.

I’m using the same users table from my previous post on stored procedures. Click on the link above to access that post and copy the create statement. I’m using a bit more data on the users table this time for this example to work. Here’s the insert statement:

INSERT INTO users
VALUES (NULL, ‘Joey’, ‘Rivera’), (NULL, ‘John’, ‘Doe’), (NULL, ‘Joey’, ‘Tester’),
(NULL, ‘Joey’, ‘Test’), (NULL, ‘Billy’, ‘Bob’);

The code is pretty simple, pretty much you want to do two queries. The first calls the stored procedure and passes in both variables. This first query will return a recordset (the second select statement in the body of the stored procedure. The next query will select totalUsers to get that variable and display it. Here’s the php code to do this in both mysql and pdo_mysql:

MySQL

$mysql = mysql_connect(‘localhost’, ‘test’, ‘test’, false, 65536);
mysql_select_db(‘test’, $mysql);
$rs = mysql_query("call get_users(‘joey’, @total);");
while($row = (mysql_fetch_assoc($rs)))
{
print_r($row);
echo
;
}
// now get the @total var
$rs2 = mysql_query("select @total;");
$total = mysql_fetch_assoc($rs2);
print_r($total);


Fuente: http://www.joeyrivera.com/2009/using-mysql-stored-procedure-inout-and-recordset-w-php/

Comentarios