Вы находитесь на странице: 1из 14

Stored Procedure

Stored Procedure (SP)


Put simply, a Stored Procedure ("SP") is a
procedure (written in SQL and other control
statements) stored in a database which can be
called by the database engine and connected
programming languages.
Advantages
• Firstly, it reduces the network traffic and overhead. In a
typical PHP database web application, there are four layers:
 The client layer, which is normally a web browser. It receives
user interactions and presents the data in a UI.
 The web server layer, which handles and dispatches user
requests and sends back responses to the client layer.
 The PHP layer, which handles all PHP interpretation, does the
application logic and generates the PHP part of response.
 The database layer, which handles all database queries,
including but not limited to a SELECT query,
an INSERT statement, etc.
In a typical environment, these layers will most likely not
reside on one single machine, maybe not even in one
network, for larger applications.
Although network speed has tremendously increased in the
past few years, it is still the slowest and most
unreliable compared to other ways of transferring the data
(CPU cache, memory, hard disk, etc). So, to save bandwidth
and increase robustness, it is sometimes a good idea to
have more processing and logic done on the server side (in
particular, the MySQL server) and have less data transferred
through the network.
Advantages

• Secondly, it improves the performance.

SP is stored and run directly in the MySQL server. It can be


pre-compiled and analyzed by the database server. This is
quite different from issuing the same query from the client
side, where the query will be parsed by database drivers,
analyzed and optimized (if possible) every time the query
statement is called. This is somehow quite like the
interpreted language execution (at the client end) and the
compiled language execution (at the database server end).
And we know a compiled program will run faster.
Advantages
• Third, Write Once and Execute Anywhere.

SQL is standard and purely 100% platform


independent. It only relies on the database server.
Consider how many different languages/libs there are
that we can use to deal with the database. It increases
efficiency to put the data retrieving and processing at the
server end instead of writing the same processing logic in
a different syntax provided by all these languages/libs, if
the data processing logic is so commonly used.
Advantages
• Last but not least, SP is a fundamental aspect of database
security.

Let's consider a simple database setup. In a human


resource information system (HRIS), it is reasonable to
assume that there exists a table holding the salary
information of each employee. An HR employee should have
the right to grab some figures out of this table: total salary,
average salary, etc but this employee should not see the
detailed salary of each employee as this information will be
too sensitive and should only be available to a few.
We know MySQL has a comprehensive privilege control. In this
case, it is obvious that we can't even grant SELECT privilege to this
HR employee (which, if we do, means he/she can see the detailed
salary of everyone). But if he/she can't access the salary table,
how can this employee get the aggregation information related
to salary? How can we allow the employee to grab that
information without compromising the HR policy?
The answer is using a Stored Procedure that returns the
required information and grants that employee
the EXECUTE privilege.

SP is now a bridge, bridging the user (our HR employee) and


the table (salary), to which the user has no direct access.
Creating a Stored Procedure in MySQL

CREATE TABLE `salary` ( `empid` int(11) NOT


NULL, `sal` int(11) DEFAULT NULL, PRIMARY KEY
(`empid`) ) ENGINE=InnoDB DEFAULT
CHARSET=utf8;
And for the HR employee that needs to get the
aggregated information on salary (average, max, min,
etc) from that table, we first create a user 'tr' like
this:

CREATE USER 'tr'@'localhost' IDENTIFIED BY 'mypass';

And for this user, we only grant EXECUTE privilege


to the schema where the salarytable resides:

grant execute on hris.* to tr@`localhost`


Create the SP
DELIMITER $$
CREATE PROCEDURE `avg_sal`(out avg_sal
decimal)
BEGIN
select avg(sal) into avg_sal from salary; END
To test if the user tr can actually run the SP
but should not be able to access the salary table,
we can switch the role by logging into the
MySQL server using user tr.

After logging in as tr, the first thing we will


notice is that the user will not be able to see any
tables and can only see the SP:
It is clear that the user tr won't be able to select
anything from any table (thus unable to see the
detailed salary number of the salary table) but
he/she is able to execute the SP we just created
and get the average salary of the company:

call avg_sal(@out);
select @out;
Calling a Stored Procedure from PHP
$dbms = 'mysql';
//Replace the below connection parameters to fit your
environment
$host = '192.168.1.8';
$db = 'hris'; $user = 'tr';
$pass = 'mypass';
$dsn = "$dbms:host=$host;dbname=$db";
$cn=new PDO($dsn, $user, $pass);
$q=$cn->exec('call avg_sal(@out)');
$res=$cn->query('select @out')->fetchAll();
print_r($res);

Вам также может понравиться