SQL 查询在通过 phpmyadmin 进行测试时工作正常,但在 PHP PDO 中尝试相同的事情时失败

Posted

技术标签:

【中文标题】SQL 查询在通过 phpmyadmin 进行测试时工作正常,但在 PHP PDO 中尝试相同的事情时失败【英文标题】:SQL query works fine when testing through phpmyadmin but fails when attempting the same thing in PHP PDO 【发布时间】:2018-03-04 00:43:50 【问题描述】:

好的,来自here 上的另一个用户问题我有以下问题:

set @test = 0, @id=0, @count=0;
select m.id, max(count)
from (
select 
 @count := if(TookTest = 1 and PatientID = @id, @count+1, 0) as count,
 @test := Tooktest,
 @id := PatientID as id
from medical) as m
group by m.id
having max(count) >=2;

这在 phpmyadmin 中运行良好,但是当我在 PDO 语句中尝试相同时,它会失败并显示以下错误消息:

PDOException: SQLSTATE[HY000]: 一般错误

$sql="set @test = 0, @id=0, @count=0;
select m.id, max(count)
from (
select 
 @count := if(TookTest = 1 and PatientID = @id, @count+1, 0) as count,
 @test := Tooktest,
 @id := PatientID as id
from medical) as m
group by m.id
having max(count) >=2;";

try
    $stmt=$dbh->prepare($sql);
    if ($stmt->execute())
        $rows=$stmt->fetchall();
    
catch(PDOException $s)
    echo $s;

我是否缺少一些东西,比如你不能在 PDO 语句中设置变量?

【问题讨论】:

mysqli / pdo 不允许您在一次执行中执行多个语句。即select * from;select count from; 【参考方案1】:

再次,它不是设置变量是它试图同时运行两个查询的问题。所以我需要把上面的代码改成这样:

$sql="set @test = 0, @id=0, @count=0;";
try
    $stmt=$dbh->prepare($sql);
    $stmt->execute()
catch(PDOException $s)
    echo $s;


$sql="select m.id, max(count)
from (
select 
 @count := if(TookTest = 1 and PatientID = @id, @count+1, 0) as count,
 @test := Tooktest,
 @id := PatientID as id
from medical) as m
group by m.id
having max(count) >=2;";

try
    $stmt=$dbh->prepare($sql);
    if ($stmt->execute())
        $rows=$stmt->fetchall();
    
catch(PDOException $s)
    echo $s;

【讨论】:

【参考方案2】:

这两个查询

set @test = 0, @id=0, @count=0;
select m.id, max(count)
from (
select 
 @count := if(TookTest = 1 and PatientID = @id, @count+1, 0) as count,
 @test := Tooktest,
 @id := PatientID as id
from medical) as m
group by m.id
having max(count) >=2;

可以重写为一个查询,因此您只需要一个 prepere 语句

  select m.id, max(count)
    from (
    select 
     @count := if(TookTest = 1 and PatientID = @id, @count+1, 0) as count,
     @test := Tooktest,
     @id := PatientID as id
    from medical) as m
    cross join ( select @test := 0, @id := 0, @count = :0 ) as init_user_params
    group by m.id
    having max(count) >=2;

【讨论】:

以上是关于SQL 查询在通过 phpmyadmin 进行测试时工作正常,但在 PHP PDO 中尝试相同的事情时失败的主要内容,如果未能解决你的问题,请参考以下文章

PHP/SQL 测试环境

通过phpMyAdmin拿webshell

导入 localhost.sql 备份 phpMyAdmin

PDO 查询不起作用,但生成的 SQL 在 PHPMyAdmin 上运行

phpMyAdmin 不允许我一次运行多个查询,并且导入我的 SQL 失败

如何将查询从 phpMyAdmin SQL Dump 转换为 sql server 易读查询