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.

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

You can also make these changes to the existing table using ALTER TABLE statements,<br />

as follows:<br />

alter table order_items type=InnoDB;<br />

alter table order_items<br />

add foreign key (orderid) references orders(orderid);<br />

To see that this change has worked, you can try to insert a row with an orderid for<br />

which there is no matching row in the orders table:<br />

insert into order_items values (77, '0-672-31697-8', 7);<br />

You should receive an error similar to<br />

ERROR 1452 (23000): Cannot add or update a child row:<br />

a foreign key constraint fails<br />

Stored Procedures<br />

A stored procedure is a programmatic function that is created <strong>and</strong> stored within<br />

<strong>MySQL</strong>. It can consist of SQL statements <strong>and</strong> a number of special control structures. It<br />

can be useful when you want to perform the same function from different applications<br />

or platforms, or as a way of encapsulating functionality. Stored procedures in a database<br />

can be seen as analogous to an object-oriented approach in programming.They allow<br />

you to control the way data is accessed.<br />

Let’s begin by looking at a simple example.<br />

Basic Example<br />

Listing 13.1 shows the declaration of a stored procedure.<br />

Listing 13.1<br />

basic_stored_procedure.sql—Declaring a Stored Procedure<br />

# Basic stored procedure example<br />

delimiter //<br />

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

BEGIN<br />

select sum(amount) into total from orders;<br />

END<br />

//<br />

delimiter ;<br />

Let’s go through this code line by line.<br />

The first statement<br />

delimiter //

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

Saved successfully!

Ooh no, something went wrong!