13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Stored Procedures<br />

317<br />

changes the end-of-statement delimiter from the current value—typically a semicolon<br />

unless you have changed it previously—to a double forward slash.You do this so that you<br />

can use the semicolon delimiter within the stored procedure as you are entering the<br />

code for it without <strong>MySQL</strong> trying to execute the code as you go.<br />

The next line<br />

create procedure total_orders (out total float)<br />

creates the actual procedure.The name of this procedure is total_orders. It has a single<br />

parameter called total, which is the value you are going to calculate.The word OUT<br />

indicates that this parameter is being passed out or returned.<br />

Parameters can also be declared IN, meaning that a value is being passed into the procedure,<br />

or INOUT, meaning that a value is being passed in but can be changed by the procedure.<br />

The word float indicates the type of the parameter. In this case, you return a total of<br />

all the orders in the orders table.The type of the orders column is float, so the type<br />

returned is also float.The acceptable data types map to the available column types.<br />

If you want more than one parameter, you can provide a comma-separated list of<br />

parameters as you would in <strong>PHP</strong>.<br />

The body of the procedure is enclosed within the BEGIN <strong>and</strong> END statements.They are<br />

analogous to the curly braces within <strong>PHP</strong> ({}) because they delimit a statement block.<br />

In the body, you simply run a SELECT statement.The only difference from normal is<br />

that you include the clause into total to load the result of the query into the total<br />

parameter.<br />

After you have declared the procedure, you return the delimiter back to being a semicolon<br />

with the line<br />

delimiter ;<br />

After the procedure has been declared, you can call it using the call keyword, as<br />

follows:<br />

call total_orders(@t);<br />

This statement calls the total orders <strong>and</strong> passes in a variable to store the result.To see the<br />

result, you need to then look at the variable:<br />

select @t;<br />

The result should be similar to<br />

+-----------------+<br />

| @t |<br />

+-----------------+<br />

| 289.92001152039 |<br />

+-----------------+<br />

In a way similar to creating a procedure, you can create a function. A function accepts<br />

input parameters (only) <strong>and</strong> returns a single value.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!