PHP PDO - 使用MySQL变量

ash*_*ash 4 php mysql sql variables pdo

我正在尝试使用PDO在PHP中运行查询.查询在顶部有一些变量来确定排名,除了在$ sql中使用SET @var时,它返回一个空行集.但是,如果我删除有问题的SQL,它返回正常.

我不想在我的脚本中返回@prev_value,@ lamb_count或@rank_increasing,只返回它在SELECT中创建的等级.

你能让我知道我做错了吗?

谢谢

    $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;
    }
Run Code Online (Sandbox Code Playgroud)

ash*_*ash 8

在这里找到解决方案: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
"; ...
Run Code Online (Sandbox Code Playgroud)