ThinkPHP执行多个存储过程解决方案
本示例介绍了在PHP中实现多个存储过程调用的具体方案,供读者参考借鉴。
回顾原生代码的实现逻辑,关键在于关闭前一个结果集,即执行类似如下操作:
$this -> queryID -> close();
若采用mysqli驱动,需对DbMysqli.class.php文件进行改造,重写query方法以实现该功能。
public function query($str) {
$this -> initConnect(false);
if (!$this -> _linkID) {
return false;
}
$this -> queryStr = $str;
//释放前次的查询结果
if ($this -> queryID)
$this -> free();
N('db_query', 1);
// 记录开始执行时间
G('queryStartTime');
$this -> queryID = $this -> _linkID -> query($str);
// 对存储过程改进
$ret = array();
$this -> debug();
if (false === $this -> queryID) {
$this -> error();
return false;
} else {
$this -> numRows = $this -> queryID -> num_rows;
$this -> numCols = $this -> queryID -> field_count;
$ret = $this -> getAll();
}
//主要将这段移动了一下,关闭结果集
if ($this -> _linkID -> more_results()) {
while (($res = $this -> _linkID -> next_result()) != NULL) {
$this -> queryID -> close();
}
}
return $ret ;
}
完成上述修改后,便可通过M函数直接调用多个存储过程或执行其他SQL指令。
在实际使用ThinkPHP时,曾遇到仅能运行首个存储过程的状况。检查Driver/Db/DbMysql.class源码后发现,虽然已对存储过程做了部分处理,但实际运行仍无效。
最终通过原生代码解决了该问题,核心代码片段如下:
$db = new mysqli(C("DB_HOST"), C("DB_USER"), C("DB_PWD"), C("DB_NAME"));
if (mysqli_connect_errno())
throw_exception(mysqli_connect_error());
$t2 = microtime(true);
echo "数据库连接用时:" . (($t2 - $t1)) . "s
";
$arr = array();
// 1st Query
$procedure = "call p1()";
$result = $db->query($procedure);
if ($result) {
// Cycle through results
while ($row = $result->fetch_object()) {
//添加到对象数组
$arr[] = $row;
}
// 这里是最重要的,需要将游标移动下一个结果集
$result->close();
$db->next_result();
}
$procedure = "call p2()";
$result = $db->query($procedure);
if ($result) {
// Cycle through results
while ($row = $result->fetch_object()) {
//添加到对象数组
$arr[] = $row;
}
// 这里是最重要的,需要将游标移动下一个结果集
$result->close();
$db->next_result();
}
期望本文所述内容能为基于ThinkPHP框架的PHP开发者提供有益帮助。