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 />

321<br />

action specified <strong>and</strong> then continue execution of the procedure. Exit h<strong>and</strong>lers exit from<br />

the nearest begin...end block.<br />

The next part of the declare h<strong>and</strong>ler specifies when the h<strong>and</strong>ler will be called. In this<br />

case, it will be called when sqlstate ‘02000’ is reached.You may wonder what that<br />

means because it seems very cryptic! This means it will be called when no rows are<br />

found.You process a resultset row by row, <strong>and</strong> when you run out of rows to process, this<br />

h<strong>and</strong>ler will be called.You could also specify FOR NOT FOUND equivalently. Other options<br />

are SQLWARNING <strong>and</strong> SQLEXCEPTION.<br />

The next thing is a cursor. A cursor is not dissimilar to an array; it retrieves a resultset<br />

for a query (such as returned by mysqli_query()) <strong>and</strong> allows you to process it a single<br />

line at a time (as you would with, for example, mysqli_fetch_row()). Consider this<br />

cursor:<br />

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

This cursor is called c1.This is just a definition of what it will hold.The query will not<br />

be executed yet.<br />

The next line<br />

open c1;<br />

actually runs the query.To obtain each row of data, you must run a fetch statement.You<br />

do this in a repeat loop. In this case, the loop looks like this:<br />

repeat<br />

...<br />

until done end repeat;<br />

Note that the condition (until done) is not checked until the end. Stored procedures also<br />

support while loops, of the form<br />

while condition do<br />

...<br />

end while;<br />

There are also loop loops, of the form<br />

loop<br />

...<br />

end loop<br />

These loops have no built-in conditions but can be exited by means of a leave; statement.<br />

Note that there are no for loops.<br />

Continuing with the example, the next line of code fetches a row of data:<br />

fetch c1 into this_id, this_amount;<br />

This line retrieves a row from the cursor query.The two attributes retrieved by the<br />

query are stored in the two specified local variables.

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

Saved successfully!

Ooh no, something went wrong!