你先需要开启pdo的扩展

C:\phpStudy\PHPTutorial\WWW\learn\db.php

<?php
require_once 'db.php';
$db = new Db;
$db->execute('set names utf8');//设置编码

$sql = 'create procedure user_data3(out count int)
begin
declare user_id int;
-- 游标标识
declare blag int default 1;
-- 游标
declare user_cursor cursor for select data.user_id from mac_user as data;
-- 处理not fount的异常
declare continue handler for not found set blag = 0;
set count = 0;
-- 打开游标
open user_cursor;
-- 执行循环
read_loop:loop
-- 获取游标中的值
fetch user_cursor into user_id;
-- 检测循环是否
if blag = 0 then
-- 跳出循环
leave read_loop;
end if;
-- if user_id = 1 then
set count = count + user_id;
-- end if;
end loop read_loop;

-- 关闭游标
close user_cursor;
-- select count;
end';


$flag = $db->execute($sql);
$sql1 = 'call user_data3(@count)';
var_dump($db->call($sql1,'select @count'));

db.php文件

<?php
/**
* 数据库DAO -->>> 对数据库进行操作的类
*/
class Db
{
/**
* 连接数据的地址
* @var string
*/
CONST DRIVER_CLASS = 'mysql:host=127.0.0.1;dbname=ipone';

/**
* 数据库的用户名
* @var string
*/
CONST USERNAME = 'root';

/**
* 数据库的密码
* @var string
*/
CONST PASSWORD = 'root';

/**
* 数据库连接出错
* @var string|array
*/
private $error = '没有异常';

/**
* 连接数据库驱动
* @var PDO
*/
private $pdo;

public function __construct()
{
try {
// 初始化执行数据库类
// jdbc:mysql://localhost:3306/"
$this->pdo = new PDO(self::DRIVER_CLASS, self::USERNAME, self::PASSWORD);
$this->pdo->query('SET NAMES UTF8');
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
// throw new \Exception($e->getMessage(), 500);
return $e->getMessage();
}
}

/**
* 读操作 -->> 查询
* @param string $sql 查询sql
* @return array 执行结果
*/
public function query($sql)
{
try {
$result = $this->pdo->query($sql);
$data = [];
foreach($result as $key => $value){
$data[] = $value;
}
return (count($data) <= 1) ? $data[0] : $data ;

} catch (PDOException $e) {
// throw new \Exception($e->getMessage(), 500);
return $e->getMessage();
}
}
/**
* [call description]
* @param string $sql 查询的语句
* @param string $select_param 参数
* @return [type]
*/
public function call($sql, $select_param = null)
{
$stmt = $this->pdo->prepare($sql);
if ($stmt->execute()) {
if (isset($select_param)) {
return $this->pdo->query($select_param)->fetchAll();
}
return true;
} else {
return false;
}
}
/**
* 执行SQL
* @param string $sql 查询sql
* @return array 执行结果
*/
public function execute($sql)
{
try {
return $this->pdo->exec($sql);
} catch (PDOException $e) {
// throw new \Exception($e->getMessage(), 500);
return $e->getMessage();
}
}

//------------------
//属性get | set 方法
//------------------

/**
* 获取系统错信息
*/
public function getError()
{
return $this->error;
}

public function write($data)
{
file_put_contents("log.txt",$data."\n",FILE_APPEND);
}
}
// $db = new Db;

执行完结果

【MySQL】使用pdo调用存储过程 --带参数输出_mysql

解释

明日在站