【问题标题】:SQL query works fine when testing through phpmyadmin but fails when attempting the same thing in PHP PDOSQL 查询在通过 phpmyadmin 进行测试时工作正常,但在 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;

标签: php mysql variables pdo phpmyadmin


【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-28
      • 1970-01-01
      • 2017-02-18
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多