在php中使用mysql存储过程以及碰到的问题解决方法

mysql 5中增加了存储过程功能,他们在php中使用很方便。
在php中调用存储过程和函数的主要步骤为。

一.准备存储过程的参数

如果存储过程有输入参数,则需要声明一个mysql变量,让mysql服务器知道此变量的存在,执行mysql语句 mysql_query(“set @mysqlvar =$phpvar”);
就可以在mysql服务器里面就有一个变量@mysqlvar。如果时IN参数,那么其值可以有phpvar传入。

二.调用存储过程

1.执行 call procedure()语句
也就是mysql_query(“call proceduer([var1]…)”);

2. 如果参数有OUT返回值,执行select @var,获取返回的参数结果
mysql_query(“select @var”)

接下来的操作就和php执行一般的mysql语句一样了。可以通过mydql_fetch_row()等函数获得结果。

如果是函数。 直接执行 select function() 就可以了。

———使用中碰到的问题解决——-

不能执行存储过程

在定义存储过程的时候,将存储过程类型设置为 DETERMINISTIC 。

定义的存储过程中有多个select语句,call失败

通过 mysql_error()输出错误提示 can’t return a result set in the given context
在mysql_connect连接数据库时指定 CLIENT_MULTI_RESULTS 标志。

  1. <?php
  2.     define(’CLIENT_MULTI_RESULTS’, 131072);
  3.  
  4.     $conn = mysql_connect("localhost", "root", "rootpwd",1,CLIENT_MULTI_RESULTS) or die("Could not connect: ".mysql_error($conn));
  5.     mysql_select_db("mydb", $conn) or die("Could not select database");
  6.    
  7.     $result = mysql_query("call proc_get_datas(2)", $conn);
  8.  
  9.     while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
  10.          // do something
  11.     }
  12.  
  13.      mysql_free_result($result, $conn);
  14.    
  15.     mysql_close($conn);    
  16. ?>

Popularity: 7% [?]

Related

Comments

Comments are closed.