Wondering how to use stored procedures with PHP and MySQL? So was I and here’s what I’ve learned. In this tutorial I’ll explain how to use PHP (I’m using 5.2.6) to call MySQL (I’m using 5.0.2) stored procedures using the following database extensions:
- MySQL - http://us.php.net/manual/en/book.mysql.php
- MySQLi - http://uk2.php.net/manual/en/class.mysqli.php
- PDO - http://us.php.net/manual/en/class.pdo.php
First we need to setup our enviroment which consists of a new database with one table and two stored procedures. In your db tool of choice (I’ll be using the MySQL Query Browser) create a new database named test. After you create the new database, make sure to add a user called example with password example to the database and give it read access.
Now create the table users:
CREATE TABLE `test`.`users` (
`users_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(100) NOT NULL,
`last_name` VARCHAR(100) NOT NULL,
PRIMARY KEY (`users_id`)
) ENGINE=INNODB DEFAULT CHARSET=latin1;
Before we create the stored procedures, lets put some dummy data in the users table. To do that just run the following query:
Next create the first stored procedure get_user:
DROP PROCEDURE IF EXISTS `test`.`get_user`$$
CREATE PROCEDURE `test`.`get_user`
(
IN userId INT,
OUT firstName VARCHAR(100),
OUT lastName VARCHAR(100)
)
BEGIN
SELECT first_name, last_name
INTO firstName, lastName
FROM users
WHERE users_id = userId;
END $$
DELIMITER ;
Finally create the second and last stored procedure get_users:
DROP PROCEDURE IF EXISTS `test`.`get_users`$$
CREATE PROCEDURE `test`.`get_users`()
BEGIN
SELECT *
FROM users;
END $$
DELIMITER ;
If you understand the sql above, skip this section. The first script we ran to create a database is pretty self explanitory. The second script will delete the table users if it’s already in your database then it will recreate it. The table will consist of three fields: users_id, first_name, and last_name. The insert script will create two users: ‘Joey Rivera’ and ‘John Doe’.
If stored procedures are new to you, don’t worry. They aren’t that complicated once you start playing with them. When looking at the code for the first stored procedure, drop procedure works the same way as dropping a table. First you want to check if the stored procedure is there and deleted before you recreate it. Create does just that, create the stored procedure in the database. get_user has three parameters: userId, firstName, and lastName. IN means when this stored procedure is called, this variable should be passed with a value. OUT means after the stored procedure executes, it will set the OUT variables with a value that can then be retrieved. You can also have INOUT variables but we don’t need them for this example.
The blulk of the code for the stored procedure goes in the BEGIN to END block. get_user is selecting the first and last name fields from the table users where the user id is equal to the userId variable being passed in. The other thing happening here is the two OUT variables are getting the values retrieved from the select statement. Variable firstName is set to the field first_name and lastName is being set to last_name. That’s it for get_user. get_users doesn’t have any IN nor OUT variables. When that stored procedure is executed it will return a recordset instead of variables.
Now that we have our environment set, we are ready to start our tests. Depending on what you are trying to achieve, you may be using mysql, mysqli, or PDO. I’m going to run the same tests with all three to show you the difference as well as the limitation of mysql compared to mysqli and PDO. One of the tests I’ll be running doesn’t work with mysql while all the tests work with mysqli and PDO.
The three tests will be:
- A simple select statement
- Calling stored procedure passing IN variable and retrieve OUT variables – get_user
- Calling stored procedure with no parameters and returns a recordset – get_users
Below is the code to run all three tests with each of the database extensions:
// MYSQL
$mysql = mysql_connect(‘localhost’, ‘example’, ‘example’);
mysql_select_db(‘test’, $mysql);
print ‘<h3>MYSQL: simple select</h3>’;
$rs = mysql_query( ‘SELECT * FROM users;’ );
while($row = mysql_fetch_assoc($rs))
{
debug($row);
}
print ‘<h3>MYSQL: calling sp with out variables</h3>’;
$rs = mysql_query( ‘CALL get_user(1, @first, @last)’ );
$rs = mysql_query( ‘SELECT @first, @last’ );
while($row = mysql_fetch_assoc($rs))
{
debug($row);
}
print ‘<h3>MYSQL: calling sp returning a recordset – doesn\’t work</h3>’;
$rs = mysql_query( ‘CALL get_users()’ );
while($row = mysql_fetch_assoc($rs))
{
debug($row);
}
// MYSQLI
$mysqli = new mysqli(‘localhost’, ‘example’, ‘example’, ‘test’);
print ‘<h3>MYSQLI: simple select</h3>’;
$rs = $mysqli->query( ‘SELECT * FROM users;’ );
while($row = $rs->fetch_object())
{
debug($row);
}
print ‘<h3>MYSQLI: calling sp with out variables</h3>’;
$rs = $mysqli->query( ‘CALL get_user(1, @first, @last)’ );
$rs = $mysqli->query( ‘SELECT @first, @last’ );
while($row = $rs->fetch_object())
{
debug($row);
}
print ‘<h3>MYSQLI: calling sp returning a recordset</h3>’;
$rs = $mysqli->query( ‘CALL get_users()’ );
while($row = $rs->fetch_object())
{
debug($row);
}
// PDO
$pdo = new PDO(‘mysql:dbname=test;host=127.0.0.1′, ‘example’, ‘example’);
print ‘<h3>PDO: simple select</h3>’;
foreach($pdo->query( ‘SELECT * FROM users;’ ) as $row)
{
debug($row);
}
print ‘<h3>PDO: calling sp with out variables</h3>’;
$pdo->query( ‘CALL get_user(1, @first, @last)’ );
foreach($pdo->query( ‘SELECT @first, @last’ ) as $row)
{
debug($row);
}
print ‘<h3>PDO: calling sp returning a recordset</h3>’;
foreach($pdo->query( ‘CALL get_users()’ ) as $row)
{
debug($row);
}
function debug($o)
{
print ‘<pre>’;
print_r($o);
print ‘</pre>’;
}
?>
When you run this code you get the following results:
Array
(
[users_id] => 1
[first_name] => Joey
[last_name] => Rivera
)
Array
(
[users_id] => 2
[first_name] => John
[last_name] => Doe
)
MYSQL: calling sp with out variables
Array
(
[@first] => Joey
[@last] => Rivera
)
MYSQL: calling sp returning a recordset – doesn‘t work
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in ***test.php on line 24
MYSQLI: simple select
stdClass Object
(
[users_id] => 1
[first_name] => Joey
[last_name] => Rivera
)
stdClass Object
(
[users_id] => 2
[first_name] => John
[last_name] => Doe
)
MYSQLI: calling sp with out variables
stdClass Object
(
[@first] => Joey
[@last] => Rivera
)
MYSQLI: calling sp returning a recordset
stdClass Object
(
[users_id] => 1
[first_name] => Joey
[last_name] => Rivera
)
stdClass Object
(
[users_id] => 2
[first_name] => John
[last_name] => Doe
)
PDO: simple select
Array
(
[users_id] => 1
[0] => 1
[first_name] => Joey
[1] => Joey
[last_name] => Rivera
[2] => Rivera
)
Array
(
[users_id] => 2
[0] => 2
[first_name] => John
[1] => John
[last_name] => Doe
[2] => Doe
)
PDO: calling sp with out variables
Array
(
[@first] => Joey
[0] => Joey
[@last] => Rivera
[1] => Rivera
)
PDO: calling sp returning a recordset
Array
(
[users_id] => 1
[0] => 1
[first_name] => Joey
[1] => Joey
[last_name] => Rivera
[2] => Rivera
)
Array
(
[users_id] => 2
[0] => 2
[first_name] => John
[1] => John
[last_name] => Doe
[2] => Doe
)
As you can see from the results above, mysql could not get the recordset returned by the stored procedure while mysqli and PDO could. After some more research, some people mentioned (Bob’s World, php.net) that by adding ‘false,65536′ to the end of the mysql_connect line, mysql could then get recordsets from stored procedures. I tried this and in fact it does work. So by changing
to:
all the different database extensions work on all tests. So in the end, it seems all of these can work with stored procedures just as well.
Get the PHP code file: test.php
Get the DB script file: php_sp_example.sql
I hope this was helpful and feel free to leave any questions or comments.
EDIT: I have made a new post about doing the above but with a stored procedure that has in/out params as well as returns a recordset. Post at: Using MySQL stored procedures with in/out and returns a recordset






#1 by Apurba Mondal on March 3, 2009 - 7:24 am
Quote
Hi Joey Rivera,
Lots of thanks for your helpful document.
Thanks
Apurba Mondal
#2 by Hadi Susanto on March 13, 2009 - 10:35 pm
Quote
Hi Joey
Thanks for the sample and explanation it’s really help me a lot
#3 by d3d1n on March 25, 2009 - 1:11 am
Quote
Hi joe…
Thanks a lot…
#4 by zsw on April 13, 2009 - 8:17 pm
Quote
Thanks
#5 by Oliver Kiss on April 20, 2009 - 2:41 pm
Quote
Thank you, great tutorial
#6 by Adolfo on April 22, 2009 - 11:33 am
Quote
I would like to know how to fix this problem PROCEDURE test.usuarios can’t return a result set in the given context , the table test just have two camps … usuario and pass then the procedure is a simple select * from usuarios the php looks like it
$resultado=mysql_query(‘CALL usuarios()’)or die(mysql_error().”\n”);
while($resfila=mysql_fetch_assoc($resultado)){
debug($resfila);
}
#7 by Joey Rivera on April 22, 2009 - 12:42 pm
Quote
Try adding: ‘,false,65536′ to the end of your mysql_connect. That fixed it for me:
$mysql = mysql_connect(‘localhost’, ‘example’, ‘example’,false,65536);
#8 by ragga on April 23, 2009 - 2:34 pm
Quote
thanx, Joey! frankly – the best resource online on stored procedures and triggers, helped me a lot. good luck.
Pingback: MySQL Stored Procedures with PHP @ Ryan Forry Consulting
#9 by Linxon on May 10, 2009 - 12:36 pm
Quote
Thanks for your tutorial.
#10 by Arun.S.S on May 11, 2009 - 5:33 am
Quote
Great and simple tutorial.
Thanks…
#11 by Jimm on May 18, 2009 - 1:10 pm
Quote
Hello. Thanks for the great information.
I like the procedures with no parameters where you get the result set with one call to $mysqli->query(). For that to happen, do there have to be no parameters at all, or will it work if there are no OUT parameters, just IN parameters?
#12 by Jimm on May 18, 2009 - 1:58 pm
Quote
I got it working. The answer is yes, with no OUT parameters and only IN parameters, it will return a result set with multiple rows.
Thanks
#13 by Siva Prem on May 22, 2009 - 3:54 am
Quote
Thanks alot for this simple tutorial.. it was very helpful.
#14 by awwam on May 27, 2009 - 3:13 am
Quote
Hey Joey, thanks a lot for the awesome tutorial,
best regards
#15 by Kristine Marie on May 29, 2009 - 3:56 am
Quote
Hello…thanks for the info. It helps a lot to me… God bless
#16 by Borubar on June 6, 2009 - 9:39 am
Quote
JOEY THANKS !! you have changed my life
#17 by Sumit Joshi on June 12, 2009 - 6:25 am
Quote
Great Joey Rivera,
Thank you very much dude!!!! You did great job………
Since from long time I was looking for Stored Procedure in PHP.
I searched lots of sites and no site could gave me help…but you have done it………
Really great effort….You have given great blessings to PHP programmers….
Againg very very very thank you……
Sumit Joshi,
sumitjoshi@themacrosoft.com
#18 by Rachit Anand on June 15, 2009 - 1:29 am
Quote
Hi Joey,
Am transiting from Oracle to MySQL so am very accustomed to the way Oracle works. And thus am a bit confused about this. In oracle these stored procedures exist in the DB and we just throw a call for them. Is it that in MySQL as well they are stored in the DB? And if it is so then we are supposed to compile these stored procedures just once before we start using them. If it is so when and where do we compile them ? Or is it that these stored procedures are to be compiled everytime they are called ?
#19 by Joey Rivera on June 15, 2009 - 8:11 am
Quote
Rachit, stored procedures in MySQL are also stored on the database. You create them once and execute when needed. Running the ‘CREATE PROCEDURE’ scripts above will store the routine in a table in the DB. Here are a couple great resources with more information:
Using Stored Routines:
http://dev.mysql.com/doc/refman/5.0/en/stored-routines.html
Stored Procedures and Function FAQ:
http://dev.mysql.com/doc/refman/5.0/en/faqs-stored-procs.html
#20 by Ed on June 20, 2009 - 7:15 am
Quote
Thanks a lot for clearing sp out for me!
#21 by Rachit Anand on June 21, 2009 - 2:00 am
Quote
Thanks a lot for your help Joey.
#22 by Steve on July 13, 2009 - 7:04 am
Quote
Thanks a lot mann totally appreciate it
#23 by Sourav ghosh on July 22, 2009 - 5:05 am
Quote
The code is not giving me desired output. May be i suspect this b’cos the engine type is still showing MYISAM instead of INNODB.Could someone help me out in resolving the issue.
I am getting the following output :-
MYSQL: simple select
FIRST NAME :: Joey === LAST NAME ::Rivera
FIRST NAME :: John === LAST NAME ::Doe
MYSQL: calling sp with out variables
FIRST NAME :: === LAST NAME ::
MYSQL: calling sp returning a recordset – doesn’t work
#24 by Joey Rivera on July 22, 2009 - 10:00 am
Quote
Using MyISAM over InnoDB shouldn’t affect this test. My recommendation would be to make sure the stored procedure is working on the database first. I use MySQL query browser but you can try the command prompt if you are comfortable with it. In query browser, I click on the transaction button first, then run ‘call get_user(1, @first, @last)’. Then I click on the next line and run ’select @first, @last’ and I see the expected results (@first = Joey, @last = Rivera). Are you getting this?
Also, try turning on error reporting on for all in PHP to see if you are getting some warning that may explain why this isn’t working correctly: http://us.php.net/manual/en/function.error-reporting.php
#25 by Valentina on July 30, 2009 - 7:41 am
Quote
Great resources! Thanks! Working properly!
Only: If I have store procedure with parameter In and parameter Out and this store procedure must return more then 1 record then it doesn’t work (Error from page -Result consisted of more than one row). I am using MySQL and php. Connection to MySQL database $mysql = mysql_connect(‘localhost’, ‘example’, ‘example’,false,65536);
Can somebody help me resolve this problem? How I can get multi results from storeprocedure with in and out parameters?????
#26 by Joey Rivera on July 30, 2009 - 10:51 am
Quote
Valentina, I’ll post some more later with an example – maybe as a new blog post, on how to do what you are asking. Pretty much, you do a mix of the in/out sp plus the recordset examples above.
#27 by Valentina on July 30, 2009 - 1:57 pm
Quote
Dear Joey! I was impress how fast you responded for my request. Thanks a lot!
I play a lot around this problem. I am not PHP or MySQL guru. I am more familiar with SQL Store Procedures.
Looks like sometning Is missing if I try get result from SP that have IN parameters and OUT parameters. Your example for SP get_user is working OK, but for example you need get last_name for all of users with first_name like ‘John’.
This is my code:
1. Add couple users with same name:INSERT INTO `test`.`users` VALUES (null, ‘John’, ‘Smith’), (null, ‘John’, ‘Dream’);
2. Create SP with IN and OUT parameters:DELIMITER $$
DROP PROCEDURE IF EXISTS get_lastname_user $$
CREATE PROCEDURE get_lastname_user
(
IN firstName VARCHAR(100),
OUT lastName VARCHAR(100)
)
BEGIN
SELECT last_name
INTO lastName
FROM users
WHERE first_name = firstName;
END $$
DELIMITER ;
call get_lastname_user(‘Joey’, @OUT);
select @OUT as Last_Name;
You will be get Last_Name – Rivera.
But if you pass IN ‘John’ then
error coming: #1172 – Result consisted of more than one row .
How get all records in this situation???? What is missing??? Could somebody help me resolve this issue??
#28 by Joey Rivera on July 30, 2009 - 10:25 pm
Quote
Valentina, the reason you are getting that error message is because the stored procedure is trying to set the variable lastName to a field value last_name but it can only do that for 1 row. Since your select is bringing back multiple rows it’s breaking. I just created a new post explaining how to do what you are asking for – using a stored procedure with in/out vars that also returns a recordset:
http://www.joeyrivera.com/2009/using-mysql-stored-procedure-inout-and-recordset-w-php/
I hope this new post will answer your question.
#29 by Mac on July 31, 2009 - 6:24 am
Quote
Dear Joey Rivera,
Thanks for such useful document. It clear my doubts regarding stored procedure.
How we can determine that use of stored procedure reduces execution time of web page? And one more thing I want to know does it good to give load on mysql instead of php?
#30 by Joey Rivera on July 31, 2009 - 9:27 am
Quote
Personally I don’t use stored procedures to reduce load time, I do it to organize my application better (as well as other reasons). I like having the db take care of itself and have the least amount of queries in my code. It almost makes it feel like the db can function as a standalone ‘app’ with any code you want to build around it.
To answer your question though, I do care about load time and I’m always working on optimizing code or queries to get the fastest execution times. For my projects I always use caching. Once the stored procedure is optimized and runs great – you can use explain to check your queries (http://dev.mysql.com/doc/refman/5.0/en/explain.html), my code will cache the results returned by the stored procedure so I don’t have to keep calling it unnecessarily. If the data changes, then I clear the cache file and query the sp again.
I also – in my development environment, print out all the queries I run per page, how long each query took, and how long each page took to execute. Here’s an example of the data I post for me to analyze and make sure things are running fast:
connect
CALL sp_user_select_view(10000, @id, @msg);
SELECT @id, @msg;
CALL sp_bio_user_select(10000, 1, @id, @msg);
SELECT @id, @msg;
Executed 5 queries in 0.0021560192108154 seconds
Average query length: 0.00043120384216309 seconds
Queries per second: 2319.0887979653
Longest query length: 0.00091314315795898
Longest query: connect
page load time: 0.092291116714478 (tracks how long the page took to completely execute)
As you can tell, the stored procedures are running extremely quick, they don’t slow down the load times at all. Connecting to the db was the slowest part. In reality my biggest load is the Zend Framework itself which is no issue to me since it offers so much and it’s not too bad of a hit anyways. I use a method in the ZF to display this information but you can get it from the basic mysql class in php as well. The page load time is simply a starttime before anything gets called and then an endtime when the page is done and I show the difference.
Your second question is whether to do more heavy lifting in code or in the database. This probably depends on the application but for things I’ve done, I know I will be using caching so I know I won’t be hitting the database as much and put a bit more work in the database end by using the stored procedures. I tend to run a couple extra queries in my stored procedures to validate data and error check instead of relying on the data coming from the code. I validate in code as well, but I want my database to work as a standalone and not rely on an outside source.
#31 by Reggie on August 5, 2009 - 4:47 am
Quote
Thanks Joey Rivera… this is really educating…
#32 by Reggie on August 7, 2009 - 9:53 am
Quote
Hi Joey,
May I request for a tutorial for using zend framework.. i’d like to learn that technology but I dont know where to start… already downloaded zend zip files, wamp, eclipse, and tomcat 5.5 as required from another website… Your tutorial is pretty much simpler than all of those I downloaded so I would like to request from you.
#33 by Joey Rivera on August 7, 2009 - 2:24 pm
Quote
Reggie, I’ll give this one some thought but it won’t be easy. I myself read two books on the zend framework before I felt comfortable enough to use for real projects. Now I find it easy to use and understand how it works but it took some playing around to get there. I started by doing their quick start first to get a general idea of how it works:
http://framework.zend.com/docs/quickstart
And these are the two books I read, there are probably newer ones out now:
Zend Framework in Action
php/architect’s Guide to Programming with Zend Framework
Now every time I work with zend, I keep their reference guide open in another window to check methods, properties, examples, etc quickly:
http://framework.zend.com/manual/en/
#34 by Paul on September 22, 2009 - 4:07 pm
Quote
hey joey,
just wondering if this is the correct way to call a stored procedure via the mysqli class?.
$mysqli = new mysqli(“localhost”,”user”,”ps”,”db”);
$rs = $mysqli->query(‘CALL updateResultsByEvent(?,?,?,?)’,
array($id,$event->name,$event->distance,$event->unit));
I seem to have trouble mapping my parameter values into the stored procedure input params, and was wondering can you spot anything.
#35 by Joey Rivera on September 22, 2009 - 7:55 pm
Quote
Hi Paul,
I don’t think you can pass an array like that to the mysqli->query although I haven’t used it much. You can try binding params using a prepare statement:
http://us.php.net/manual/en/mysqli.prepare.php
You could also escape each variable individually and pass the variables to your query. For example:
// escape vars
$event = $mysqli->real_escape_string($event);
$unit = $mysql->real_escape_string($unit);
// then call sp
$rs = $mysqli->query(‘CALL updateResultsByEvent($id,$event,$distance,$unit)’);
http://us.php.net/manual/en/mysqli.real-escape-string.php
#36 by Thalia on September 25, 2009 - 10:18 am
Quote
Thank you so very much for sharing this tutorial!
#37 by Hossam on September 30, 2009 - 9:31 am
Quote
hey Joey,
can we use the same stored procedure to get both output parameters passed and result set.
for example lets reformat the SP called “get_user” to the following
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`get_user`$$
CREATE PROCEDURE `test`.`get_user`
(
IN userId INT,
OUT firstName VARCHAR(100),
OUT lastName VARCHAR(100)
)
BEGIN
SELECT first_name, last_name
INTO firstName, lastName
FROM users
WHERE users_id = userId;
select * from users where users_id = userId;
END $$
DELIMITER ;
—————————–
then use
$result = mysql_query ( “call get_user (1, @firstName, @lastName)” );
$result2 = mysql_query ( “select @firstName, @lastName” );
where variable $result represents the result set
while variable $result2 represents the output parameters
i’ve tried this code already and didn’t get the both. any mistake here? or is there another method to get what i want (result set and out params from the same Stored Procedure) ?
#38 by Joey Rivera on October 3, 2009 - 11:41 am
Quote
Hey Hossam, actually you can. Here is a post talking more about that topic in detail:
http://www.joeyrivera.com/2009/using-mysql-stored-procedure-inout-and-recordset-w-php
I found that trying to do this didn’t always work with the mysql adapter depending on your mysql driver version. But your code seems correct.
#39 by RoverWhite on October 9, 2009 - 7:25 am
Quote
With mysql extension You will be unable to execute stored procedure returning record set twice or more. As a result of second call to mysql_query you will get Error: “Commands out of sync; you can’t run this command now”.
This because of calling to stored procedures treated as multi result set query and you need to tell mysql to give you next result.
Solution is using mysqli extension, and mysqli functions or object methods:
- mysqli_multi_query
- mysqli_use_result
- mysqli_store_result
- mysqli_more_results
- mysqli_next_result.
After each call to stored procedure and getting result set, you need to call mysqli_next_result and check if there more results with mysqli_more_results.
Somethink like this:
print ‘MYSQLI: calling sp returning a recordset’;
$rs = $mysqli->query( ‘CALL get_users()’ );
while($row = $rs->fetch_object())
{
debug($row);
}
$mysqli->next_result();
while ($mysqli->more_results())
{
$mysqli->next_result();
}
print ‘MYSQLI: calling sp returning a recordset’;
$rs = $mysqli->query( ‘CALL get_users()’ );
while($row = $rs->fetch_object())
{
debug($row);
}
$mysqli->next_result();
while ($mysqli->more_results())
{
$mysqli->next_result();
}
You also can get multiple recordsets from one stored procedure, if you want, i suppose.
#40 by AntKlim on October 29, 2009 - 9:15 am
Quote
Hello Joey,
Thanks for your tutorials. I hope you can help me with my problem.
I have a stored procedure:
delimiter |
drop procedure if exists pget_info2 |
create procedure pget_info2 ()
begin
declare mheadid int;
declare mhdname char(50);
declare mhdstat char(1);
declare mnorows boolean;
declare mnmrows int default 0;
declare ckbhead cursor for
select headid, hdname, hdstat
from kbhead
where headid <= 10;
declare continue handler for not found
set mnorows = true;
open ckbhead;
select found_rows() into mnmrows;
the_loop: loop
fetch ckbhead
into mheadid, mhdname, mhdstat;
if mnorows then
close ckbhead;
leave the_loop;
end if;
set mhdname := concat(mhdname, ‘_test’);
select mheadid, mhdname, mhdstat;
end loop the_loop;
end |
delimiter ;
When I call this procedure from mysql command line I receive all rows from cursor. But when I call this procedure from PHP-script I receive only one row (the first row from cursor).
This is my PHP-script:
$conn = mysql_connect(‘localhost’, ‘xxxx’, ‘xxxx’, false, 65536);
mysql_select_db(‘xxxx’, $conn);
$rs = mysql_query(“call pget_info2();”);
while ($row = (mysql_fetch_assoc($rs)))
{
print_r($row);
echo “”;
}
mysql_close($conn);
How I can receive all rows from stored procedure? Maybe I do some mistakes?
In advance thanks.
P.S. Excuse for my English
#41 by Michael on November 2, 2009 - 11:27 pm
Quote
hi joe
Its very nice for beginners
Thanks a lot
#42 by Christian Ogalabu on November 4, 2009 - 3:59 am
Quote
Hello Joey,
I think you should write a book. Your explanations on matters that arises are wonderful. please am developing an Application for a private telecommunications company. Please, I need tutorials on “caching and procedures” for mySQL or mySQLi. My Server machine is slow now as much people are query the Database.
Thank
#43 by Joey Rivera on November 4, 2009 - 4:20 pm
Quote
Christian,
Thank you. I actually like the idea of writing a blog post on caching. I’ll probably do that next.
#44 by Danielle on November 11, 2009 - 12:14 am
Quote
Hi Joey,
Thank you for your blog, your site has been the only one that has provided me with any success whatsoever.
I’ve modified your example code to fit my own needs and for some reason, I’m still unable to have my OUT variables to return. I’m at a loss as my procedure is as simple as they come. My test case and example has been driving me crazy therefore I figured it may be time for me to reach out for some assistance.
Stored Procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS `UpgradeAvailable` $$
(
IN Platform VARCHAR(45),
IN Version VARCHAR(20),
OUT Version_ID INT(10),
OUT DownloadURL VARCHAR(250))
BEGIN
SELECT Pinglet_Version_ID, VersionDownloadURL
INTO Version_ID, DownloadURL
FROM Version_Table PV
WHERE PV.Platform = Platform
AND PV.Version = Version;
END $$
DELIMITER ;
I’ve thrown together a form to pass various values into the procedure call:
Platform:
Version:
A modification to your PHP page to display the results of your Stored Procedure Call:
<?php
// MYSQL
$mysql = mysql_connect(‘host’, ‘user’, ‘pass’); //,false,65536 // add this to fix issue with recordsets
mysql_select_db(‘database’, $mysql);
print ‘MYSQL: simple select’;
$rs = mysql_query( ‘SELECT * FROM Version_Table;’ );
while($row = mysql_fetch_assoc($rs))
{
debug($row);
}
print ‘Print Post Variables’;
print ‘Platform IN ‘;
debug($_POST[Platform]);
print ‘Version IN ‘;
debug($_POST[Version]);
print ‘MYSQL: calling sp with out variables’;
$rs = mysql_query( ‘CALL UpgradeAvailable($_POST[Platform], $_POST[Version], @Version_ID, @DownloadURL)’ );
$rs = mysql_query( ‘SELECT @Version_ID, @DownloadURL’ );
while($row = mysql_fetch_assoc($rs))
{
debug($row);
}
function debug($o)
{
print ”;
print_r($o);
print ”;
}
?>
You can access this temporary page demonstrating the above pages that I have published by accessing the http://pinglet.mobi/usage.data/spform.html with the following parameters:
Platform: ‘Joeys Example’
Version: ‘1.0′
Please let me know if you have any questions and thanks again for your willingness to help others.
Danielle
#45 by Joey Rivera on November 11, 2009 - 11:52 am
Quote
Danielle,
I think you are having the same issue Valentina commented on my post about in/out vars with mysql and php:
http://www.joeyrivera.com/2009/using-mysql-stored-procedure-inout-and-recordset-w-php/#comment-479
What she did was store the ‘out’ values in a temporary table and then query them. It seems that depending on what mysql driver you are using (you can get the number by checking your phpinfo() and looking for client api under mysql I believe) you may not be able to get the out variables back. Try using PDO if you have that installed since I haven’t had this issue using PDO. Unfortunately, I haven’t spent much time trying to find any better workaround using the mysql adapter.
#46 by Mudassir on November 29, 2009 - 11:59 am
Quote
Hi Joey Rivera
Thanks for your nice blog post. this really help me a lot.
#47 by shailesh thapa on December 8, 2009 - 1:48 am
Quote
hi Joey, i am greatful of your article, i learnt the sp from this article and now using it, i have one problem -when i am using sp on multiple time it is not working so please tell us the reason and solution of that.
shailesh
#48 by Joey Rivera on December 8, 2009 - 11:11 am
Quote
Shailesh,
I’m glad you found this helpful. Could you give me some more information on what exactly you are trying to do and what isn’t not working? Maybe post an example. Are you getting an error message? Does you example work in a MySQL tool and not in PHP?
#49 by Jick Libot on December 10, 2009 - 10:18 pm
Quote
This helps me a lot! Thanks bro! nway. I want to control the result by in html, may i know how to convert the result to string?