11.07.2015 Views

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

SHOW MORE
SHOW LESS
  • No tags were found...

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

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

CHAPTER 32 • STORED ROUTINESwww.it-ebooks.infoSQL SECURITY {DEFINER | INVOKER}If the SQL SECURITY characteristic is set to DEFINER, then the procedure will be executed in accordancewith the privileges of the user who defined the procedure. If it’s set to INVOKER, it will execute accordingto the privileges of the user executing the procedure.You might think the DEFINER setting is a tad strange and perhaps insecure. After all, why wouldanyone want to allow a user to execute procedures using another user’s privileges? This is actually agreat way to enforce, rather than abandon, security of your system because it allows you to create usersthat have absolutely no rights to the database other than to execute these procedures.COMMENT 'string'You can add some descriptive information about the procedure by using the COMMENT characteristic.Declaring and Setting VariablesLocal variables are often required to serve as temporary placeholders when carrying out tasks within astored routine. However, unlike <strong>PHP</strong>, <strong>MySQL</strong> requires you to specify the type of the variables andexplicitly declare them. This section shows you how to both declare and set variables.Declaring VariablesUnlike <strong>PHP</strong>, <strong>MySQL</strong> requires you to declare local variables within a stored routine before using them,specifying their type by using one of <strong>MySQL</strong>’s supported datatypes. Variable declaration isacknowledged with the DECLARE statement, and its prototype looks like this:DECLARE variable_name type [DEFAULT value]For example, suppose a stored procedure named calculate_bonus was created to calculate anemployee’s yearly bonus. It might require a variable named salary, another named bonus, and a thirdnamed total. They would be declared like so:DECLARE salary DECIMAL(8,2);DECLARE bonus DECIMAL(4,2);DECLARE total DECIMAL(9,2);When declaring variables, the declaration must take place within a BEGIN/END block. Furthermore,the declarations must take place before executing any other statements in that block. Also note thatvariable scope is limited to the block in which it’s declared, an important point because it’s possible tohave several BEGIN/END blocks in a routine.The DECLARE keyword is also used for declaring certain conditions and handlers. This matter isdiscussed in further detail in the “Conditions and Handlers” section.Setting VariablesThe SET statement is used to set the value of a declared stored routine variable. Its prototype looks likethis:632

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

Saved successfully!

Ooh no, something went wrong!