本文章介紹了關于在php中調用mysql5的存儲過程,為什么只講mysql5呢,原因很簡單因為只有mysql5.0及以后的版本才支持存儲過程,下面我們從入門及開始看.
1,調用存儲過程的方法.
a,如果存儲過程有 IN/INOUT參數,聲明一個變量,輸入參數給存儲過程,該變量是一對,一個php變量,也可以不必,只是沒有php變量時,沒有辦法進行動態輸入,一個Mysql變量.
b,如果存儲過程有OUT變量,聲明一個Mysql變量.mysql變量的聲明比較特殊,必須讓mysql服務器知道此變量的存在,其實也就是執行一條mysql語句.
set @mysqlvar=$phpvar;
c,使用mysql_query()/mysql_db_query()執行mysql 變量聲明語句,代碼如下:
mysql_query("set @mysqlvar[=$pbpvar]");
這樣,在mysql服務器里面就有一個變量,@mysqlar,如果時IN參數,那么其值可以有phpar傳入.
d,如果時存儲過程.
1,執行 call procedure()語句.
也就是mysql_query("call proceduer([var1]...)");
2.如果有返回值,執行select @ar,返回執行結果,代碼如下:
mysql_query("select @var)"
接下來的操作就和php執行一般的mysql語句一樣了,可以通過mydql_fetch_row()等函數獲得結果,如果是函數,直接執行 select function()就可以了,代碼如下:
- $host="localhost";
- $user="root";
- $password="11212";
- $db="samp_db";
- $dblink=mysql_connect($host,$user,$password)
- or die("can't connect to mysql");
- mysql_select_db($db,$dblink)
- or die("can't select samp_db");
- $res=mysql_query("set @a=$password",$dblink);
- $res=mysql_query("call aa(@a)",$dblink);
- $res=mysql_query("select @a",$dblink);
- $row=mysql_fetch_row($res);
- echo $row[0];
從網上找的一個實例,代碼如下:
- <?php
- /* Connect to a MySQL server */
- $link = mysqli_connect(
- 'localhost', /* The host to connect to */
- 'root', /* The user to connect as */
- 'root', /* The password to use */
- 'db_name'); /* The default database to query */
- if (!$link) {
- printf("Can't connect to MySQL Server. Errorcode: %sn", mysqli_connect_error());
- exit;
- }
- /* Send a query to the server */
- if ($result = mysqli_query($link, "call se_proc('crm')")) {
- /* Fetch the results of the query */
- while( $row = mysqli_fetch_array($result) ){
- echo ($row[0]. "--------- SR. " . $row[1] . "
- ");
- }
- /* Destroy the result set and free the memory used for it */
- mysqli_free_result($result);
- } //Vevb.com
- /* Close the connection */
- mysqli_close($link);
- ?>
這個查找后會返回數據數據集.
新聞熱點
疑難解答