我正在重构一个项目,我正在做的部分工作是将内联 SQL 替换为对存储过程的调用。我遇到了一个问题。我正在使用 PHP 5.3.5 版和 MySQL 5.0.7 版
该项目有成员,成员可以有请求。我想获取特定成员的所有请求并将它们作为 Request 对象数组返回。
我创建了一个静态方法,该方法调用一个返回所有请求 id 的存储过程,然后我用它来实例化新的请求对象。问题是我收到关于无缓冲查询的错误,这是错误:
General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute
我已按照错误消息的建议完成并使用了 fetchAll,但我仍然遇到这个问题。以下是相关 PHP 的简化版本:
class Request
{
public function __construct($request_id)
{
//as you can see this is still inline
$db = Database::get_instance();
$sql = "SELECT field1,field2,field3 FROM requests WHERE request_id = ?";
$stmt = $db->prepare($sql);
$stmt->execute(array($request_id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($row))
{
//populate properties
foreach($row as $key=>$value)
{
$this->$key = $value;
}
}
}
public static function get_requests_by_member_id($member_id)
{
//array to hold results
$requests = array();
//this is just a PDO object
$db = Database::get_instance();
$sql = "CALL get_requests_by_member_id(?)";
$stmt = $db->prepare($sql);
/bind the param
$stmt->bindParam(1,$member_id,PDO::PARAM_INT,10);
$stmt->execute();
//iterate through adding new Request objects to the array
foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $row)
{
//here is where the problem occurs
$requests[] = new self($row['request_id']);
}
return $requests;
}
}
我的存储过程的简化版本:
delimiter $$
CREATE PROCEDURE get_requests_by_member_id(member_id_in INT)
BEGIN
SELECT request_id
FROM requests
WHERE cr.member_id = member_id_in;
END$$
delimiter ;
正如我上面提到的,当我尝试实例化一个新的请求以添加到数组时,就会出现问题。这似乎会导致我看到的光标问题,但是因为我使用了 fetchAll() 应该不能解决问题吗?是否有处理这种情况的最佳实践?任何建议将不胜感激。非常感谢!