13.09.2016 Views

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

320 Chapter 13 Advanced <strong>MySQL</strong> Programming<br />

Listing 13.4<br />

Continued<br />

create procedure largest_order(out largest_id int)<br />

begin<br />

declare this_id int;<br />

declare this_amount float;<br />

declare l_amount float default 0.0;<br />

declare l_id int;<br />

declare done int default 0;<br />

declare continue h<strong>and</strong>ler for sqlstate '02000' set done = 1;<br />

declare c1 cursor for select orderid, amount from orders;<br />

open c1;<br />

repeat<br />

fetch c1 into this_id, this_amount;<br />

if not done then<br />

if this_amount > l_amount then<br />

set l_amount=this_amount;<br />

set l_id=this_id;<br />

end if;<br />

end if;<br />

until done end repeat;<br />

close c1;<br />

set largest_id=l_id;<br />

end<br />

//<br />

delimiter ;<br />

This code uses control structures (both conditional <strong>and</strong> looping), cursors, <strong>and</strong> declare<br />

h<strong>and</strong>lers. Let’s consider it line by line.<br />

At the start of the procedure, you declare a number of local variables for use within<br />

the procedure.The variables this_id <strong>and</strong> this_amount store the values of orderid <strong>and</strong><br />

amount in the current row.The variables l_amount <strong>and</strong> l_id are for storing the largest<br />

order amount <strong>and</strong> the corresponding ID. Because you will work out the largest amount<br />

by comparing each value to the current largest value, you initialize this variable to zero.<br />

The next variable declared is done, initialized to zero (false).This variable is your<br />

loop flag.When you run out of rows to look at, you set this variable to 1 (true):<br />

The line<br />

declare continue h<strong>and</strong>ler for sqlstate ‘02000’ set done = 1;<br />

is called a declare h<strong>and</strong>ler. It is similar to an exception in stored procedures. Also available<br />

are continue h<strong>and</strong>lers <strong>and</strong> exit h<strong>and</strong>lers. Continue h<strong>and</strong>lers, like the one shown, take the

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

Saved successfully!

Ooh no, something went wrong!