[英]A stored procedure that doesn't work in my PHP code but it works with a SQL Client
I'm working on a business monitor (a pannel that presents some metrics). 我正在研究业务监视器(提供一些指标的面板)。 To get that data I do a sql request.
为了获得该数据,我执行了sql请求。 By the way, I used a stored procedure.
顺便说一句,我使用了一个存储过程。 My code is :
我的代码是:
public function execErrorWarnLogs($id){
try {
$sql = "exec [BUSINESS_MONITOR_LOGS] @id='".$id."'";
$req = $this->_bdd->prepare($sql);
$req->execute();
$res = $req->fetchAll(PDO::FETCH_ASSOC);
$req->closeCursor();
return $res;
} catch (Exception $e) {
echo $e->getMessage();
}
}
When I'm trying to get some data indexed by $id, I get some troubles. 当我尝试通过$ id索引某些数据时,遇到了一些麻烦。 I got an array that has null values... However, if I execute that stored procedure with an SQL client I get results.
我有一个具有空值的数组...但是,如果我使用SQL客户端执行该存储过程,则会得到结果。
Is that already happened to someone here ? 这已经发生在这里吗? Can someone explain me why I get that ?
有人可以解释一下我为什么得到这个吗?
If you want more information, please let me know. 如果您需要更多信息,请告诉我。
Thanks. 谢谢。
Is $id an integer or a string? $ id是整数还是字符串?
Try using bound parameter instead. 尝试改用绑定参数。 This is a example how it is working perfectly in my code:
这是一个在我的代码中如何完美工作的示例:
public function execErrorWarnLogs($id){
try {
$sql = "exec BUSINESS_MONITOR_LOGS @id=:id";
$req = $this->_bdd->prepare($sql);
$req->execute([
'id' => $id
]);
$res = $req->fetchAll(PDO::FETCH_ASSOC);
$req->closeCursor();
return $res;
} catch (Exception $e) {
echo $e->getMessage();
}
}
You should use parameters for security reasons, too! 您也应该出于安全原因使用参数!
Two site notes: 两个站点说明:
If you do string interpolation you don't need to prepare the statement. 如果进行字符串插值,则无需准备语句。 Then you could just do:
然后,您可以这样做:
$req = $this->_bdd->query($sql);
$res = $req->fetchAll(PDO::FETCH_ASSOC);
But the recommendet approach (for security) is to provide values as bound parameters and prepare the query. 但为安全起见,推荐方法是提供值作为绑定参数并准备查询。
As far as I know, you don't need $req->closeCursor() if you use Microsofts latest pdo driver for MSSQL. 据我所知,如果您使用Microsoft最新的pdo驱动程序用于MSSQL,则不需要$ req-> closeCursor()。 Whether you need closeCursor depends on the driver you use.
是否需要closeCursor取决于您使用的驱动程序。
My stored procedure : CREATE PROCEDURE BUSINESS_MONITOR @id VARCHAR(50) AS 我的存储过程:CREATE PROCEDURE BUSINESS_MONITOR @id VARCHAR(50)AS
BEGIN 开始
SET NOCOUNT ON;
SELECT e.METRIC_NAME, e.METRIC_VALUE
FROM MONITOR_EVENTS e
WHERE e.MAIN_ID = @id
END 结束
There are two more possible reasons: 还有两个可能的原因:
I would assume, that you have an encoding issue. 我假设您有一个编码问题。 If $id contains chars, that are out of the ascii-range, and you have another encoding, this could cause the query to fail.
如果$ id包含字符,超出了ASCII范围,并且您使用了另一种编码,则可能导致查询失败。 So check the encoding of $id and of you db connection
因此,请检查$ id和您的数据库连接的编码
Maybe you have whitespaces in you id. 也许您的ID中包含空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.