惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
News and Events Feed by Topic
L
LINUX DO - 最新话题
Help Net Security
Help Net Security
The Last Watchdog
The Last Watchdog
Attack and Defense Labs
Attack and Defense Labs
www.infosecurity-magazine.com
www.infosecurity-magazine.com
PCI Perspectives
PCI Perspectives
NISL@THU
NISL@THU
L
LINUX DO - 热门话题
K
Kaspersky official blog
P
Privacy International News Feed
Cloudbric
Cloudbric
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
C
CERT Recently Published Vulnerability Notes
A
Arctic Wolf
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
The GitHub Blog
The GitHub Blog
Blog — PlanetScale
Blog — PlanetScale
Security Archives - TechRepublic
Security Archives - TechRepublic
博客园 - Franky
博客园_首页
S
SegmentFault 最新的问题
小众软件
小众软件
G
Google Developers Blog
B
Blog
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
Project Zero
Project Zero
I
Intezer
L
Lohrmann on Cybersecurity
T
Threat Research - Cisco Blogs
V2EX - 技术
V2EX - 技术
Schneier on Security
Schneier on Security
Forbes - Security
Forbes - Security
T
Tenable Blog
T
The Blog of Author Tim Ferriss
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
M
MIT News - Artificial intelligence
量子位
The Hacker News
The Hacker News
C
Cisco Blogs
G
GRAHAM CLULEY
AWS News Blog
AWS News Blog
P
Privacy & Cybersecurity Law Blog
T
Troy Hunt's Blog
Hacker News: Ask HN
Hacker News: Ask HN
Recorded Future
Recorded Future
MyScale Blog
MyScale Blog
V
Visual Studio Blog
爱范儿
爱范儿

博客园 - N/A2011

Managing Hierarchical Data in MySQL php soapclient with wsse 转贴 MySQL Multiple Result Procs in PHP 转贴 jQuery Datepicker by Example php generate pdf open office (java) ant + emma + junit Copy all files recursively from one folder to another RecursiveFileFinder 转贴: 怎样找第一份工作 PerformanceCounter in .net Trace in .net Logger in .net 转贴: 傅立叶级数(Fourier Series) 推导 CAS in .net Encrypting and Decrypting in .net Access Control List in .net User and Data Security in .net Unmanaged code in .net
转贴 Using MySQL Stored Procedures with PHP mysql/mysqli/pdo
N/A2011 · 2010-05-01 · via 博客园 - N/A2011

转自: http://www.joeyrivera.com/2009/using-mysql-stored-procedures-with-php-mysqlmysqlipdo/

Using MySQL Stored Procedures with PHP mysql/mysqli/pdo

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:

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.

CREATE DATABASE `test`;

Now create the table users:

DROP TABLE IF EXISTS `test`.`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:

INSERT INTO `test`.`users` VALUES (NULL, ‘Joey’, ‘Rivera’), (NULL, ‘John’, ‘Doe’);

Next create the first stored procedure get_user:

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;
END $$
DELIMITER ;

Finally create the second and last stored procedure get_users:

DELIMITER $$
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:

  1. A simple select statement
  2. Calling stored procedure passing IN variable and retrieve OUT variables – get_user
  3. 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:

<?php
// 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:

MYSQL: simple select
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

$mysql = mysql_connect(‘localhost’, ‘example’, ‘example’);

to:

$mysql = mysql_connect(‘localhost’, ‘example’, ‘example’,false,65536);

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