Home Backend Development PHP Tutorial 当PHP遇到MySQL存储过程

当PHP遇到MySQL存储过程

Jun 23, 2016 pm 01:47 PM

1、MySQL存储过程

我们常用的操作数据库语言SQL语句在执行的时候需要要先编译,然后执行,而存储过程(Stored Procedure)是一组为了完成特定功能的SQL语句集,经编译后存储在数据库中,用户通过指定存储过程的名字并给定参数(如果该存储过程带有参数)来调用执行它。
一个存储过程是一个可编程的函数,它在数据库中创建并保存。它可以有SQL语句和一些特殊的控制结构组成。当希望在不同的应用程序或平台上执行相同的函数,或者封装特定功能时,存储过程是非常有用的。数据库中的存储过程可以看做是对编程中面向对象方法的模拟。它允许控制数据的访问方式。 

2、存储过程通常有以下优点:

(1)存储过程增强了SQL语言的功能和灵活性。存储过程可以用流控制语句编写,有很强的灵活性,可以完成复杂的判断和较复杂的运算。
(2)存储过程允许标准组件是编程。存储过程被创建后,可以在程序中被多次调用,而不必重新编写该存储过程的SQL语句。而且数据库专业人员可以随时对存储过程进行修改,对应用程序源代码毫无影响。
(3)存储过程能实现较快的执行速度。如果某一操作包含大量的Transaction-SQL代码或分别被多次执行,那么存储过程要比批处理的执行速度快很多。因为存储过程是预编译的。在首次运行一个存储过程时查询,优化器对其进行分析优化,并且给出最终被存储在系统表中的执行计划。而批处理的Transaction-SQL语句在每次运行时都要进行编译和优化,速度相对要慢一些。 
(4)存储过程能过减少网络流量。针对同一个数据库对象的操作(如查询、修改),如果这一操作所涉及的Transaction-SQL语句被组织程存储过程,那么当在客户计算机上调用该存储过程时,网络中传送的只是该调用语句,从而大大增加了网络流量并降低了网络负载。
(5)存储过程可被作为一种安全机制来充分利用。系统管理员通过执行某一存储过程的权限进行限制,能够实现对相应的数据的访问权限的限制,避免了非授权用户对数据的访问,保证了数据的安全。

3、PHP调用MySQL案例

实例一:无参的存储过程

$conn = mysql_connect('localhost','root','root') or die ("数据连接错误!!!");mysql_select_db('test',$conn);$sql = "create procedure myproce()beginINSERT INTO user (id, username, sex) VALUES (NULL, 's', '0');end; ";mysql_query($sql);//创建一个myproce的存储过程$sql = "call test.myproce();";mysql_query($sql);//调用myproce的存储过程,则数据库中将增加一条新记录。
Copy after login
实例二:传入参数的存储过程

$sql = "create procedure myproce2(in score int)beginif score >= 60 thenselect 'pass';elseselect 'no';end if;end; ";mysql_query($sql);//创建一个myproce2的存储过程$sql = "call test.myproce2(70);";mysql_query($sql);//调用myproce2的存储过程,看不到效果,可以在cmd下看到结果。
Copy after login
实例三:传出参数的存储过程

$sql = "create procedure myproce3(out score int)beginset score=100;end; ";mysql_query($sql);//创建一个myproce3的存储过程$sql = "call test.myproce3(@score);";mysql_query($sql);//调用myproce3的存储过程$result = mysql_query('select @score;');$array = mysql_fetch_array($result);echo '<pre class="brush:php;toolbar:false">';print_r($array);
Copy after login
实例四:传出参数的inout存储过程

$sql = "create procedure myproce4(inout sexflag int)beginSELECT * FROM user WHERE sex = sexflag;end; ";mysql_query($sql);//创建一个myproce4的存储过程$sql = "set @sexflag = 1";mysql_query($sql);//设置性别参数为1$sql = "call test.myproce4(@sexflag);";mysql_query($sql);//调用myproce4的存储过程,在cmd下面看效果
Copy after login
实例五:使用变量的存储过程 

$sql = "create procedure myproce5(in a int,in b int)begindeclare s int default 0;set s=a+b;select s;end; ";mysql_query($sql);//创建一个myproce5的存储过程$sql = "call test.myproce5(4,6);";mysql_query($sql);//调用myproce5的存储过程,在cmd下面看效果
Copy after login
实例六:case语法

$sql = "create procedure myproce6(in score int)begincase scorewhen 60 then select '及格';when 80 then select '及良好';when 100 then select '优秀';else select '未知分数';end case;end; ";mysql_query($sql);//创建一个myproce6的存储过程$sql = "call test.myproce6(100);";mysql_query($sql);//调用myproce6的存储过程,在cmd下面看效果
Copy after login
实例七:循环语句

$sql = "create procedure myproce7()begindeclare i int default 0;declare j int default 0;while i实例八:repeat语句  <p></p>  <p></p>  <pre name="code" class="sycode">$sql = " create procedure myproce8()begindeclare i int default 0;declare j int default 0;repeatset j=j+i;set i=i+1;until j>=10end repeat;select j;end; ";mysql_query($sql);//创建一个myproce8的存储过程$sql = "call test.myproce8();";mysql_query($sql);//调用myproce8的存储过程,在cmd下面看效果
Copy after login
实例九:loop语句

$sql = "create procedure myproce9()begindeclare i int default 0;declare s int default 0;loop_label:loopset s=s+i;set i=i+1;if i>=5 thenleave loop_label;end if;end loop;select s;end; ";mysql_query($sql);//创建一个myproce9的存储过程$sql = "call test.myproce9();";mysql_query($sql);//调用myproce9的存储过程,在cmd下面看效果
Copy after login
实例十:删除存储过程

mysql_query("drop procedure if exists myproce");//删除test的存储过程
Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

PHP Logging: Best Practices for PHP Log Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

HTTP Method Verification in Laravel HTTP Method Verification in Laravel Mar 05, 2025 pm 04:14 PM

Laravel simplifies HTTP verb handling in incoming requests, streamlining diverse operation management within your applications. The method() and isMethod() methods efficiently identify and validate request types. This feature is crucial for building

Discover File Downloads in Laravel with Storage::download Discover File Downloads in Laravel with Storage::download Mar 06, 2025 am 02:22 AM

The Storage::download method of the Laravel framework provides a concise API for safely handling file downloads while managing abstractions of file storage. Here is an example of using Storage::download() in the example controller:

See all articles