PHP PDO - Using MySQL Variables(PHP PDO - 使用 MySQL 变量)
问题描述
我正在尝试使用 PDO 在 PHP 中运行查询.该查询在顶部有一些变量来确定排名,除了在 $sql 中使用 SET @var 时,它返回一个空行集.但是,如果我删除有问题的 SQL,它会返回正常.
I'm trying to run a query in PHP using PDO. The query has some variables at the top to determine a rank, except the when using the SET @var in the $sql, it returns an empty rowset. If I remove the offending SQL however, it returns fine.
我不想在脚本中返回 @prev_value、@rank_count 或 @rank_increasing,只返回它在 SELECT 中创建的排名.
I don't want to return @prev_value, @rank_count or @rank_increasing in my script, only the rank it creates in the SELECT.
你能告诉我我做错了什么吗?
Can you let me know what I am doing wrong please?
谢谢
$sql = "
SET @prev_value = NULL;
SET @rank_count = 0;
SET @rank_increasing = 0;
SELECT a.*
, @rank_increasing := @rank_increasing + 1 AS row_num
, CASE
WHEN @prev_value = score
THEN @rank_count
WHEN @prev_value := score
THEN @rank_count := @rank_increasing
END AS rank
FROM (
-- INLINE VIEW --
) a
";
try {
$sth = $dbh->prepare($sql);
$sth->execute(array($var1, $var2));
return $sth->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
return $e;
}
推荐答案
在这里找到解决方案:https://stackoverflow.com/a/4685040/1266457
谢谢:)
修复:
// Prepare and execute the variables first
$sql = "
SET @prev_value = NULL;
SET @rank_count = 0;
SET @rank_increasing = 0;
";
$sth = $dbh->prepare($sql);
$sth->execute();
// Run the main query
$sql = "
SELECT a.*
, @rank_increasing := @rank_increasing + 1 AS row_num
, CASE
WHEN @prev_value = score
THEN @rank_count
WHEN @prev_value := score
THEN @rank_count := @rank_increasing
END AS rank
FROM (
-- INLINE VIEW --
) a
"; ...
这篇关于PHP PDO - 使用 MySQL 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP PDO - 使用 MySQL 变量
基础教程推荐
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01