Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO - Using MySQL Variables

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.

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?

Thanks

    $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;
    }
like image 875
ash Avatar asked Jul 25 '14 14:07

ash


People also ask

Can I use PDO with MySQL?

Unlike MySQLi, PDO is only object-oriented and supports a number of different database types that use PHP, such as MySQL, MSSQL, Informix, and PostgreSQL.

Does PDO work with MariaDB?

On the other hand, once you've mastered PDO, you can use it with any database you desire, which can be incredibly useful when switching from another database to, say, MariaDB.

What is PDO in PHP with example?

PDO in PHP (PHP Data Objects) is a lightweight, consistent framework for accessing databases in PHP. Database-specific features may be exposed as standard extension functions by any database driver that implements the PDO interface.

Does PHP 5.4 support PDO?

PDO will not run since upgrading PHP to 5.4.


1 Answers

Found the solution here: https://stackoverflow.com/a/4685040/1266457

Thank you :)

To fix:

// 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
"; ...
like image 169
ash Avatar answered Oct 19 '22 07:10

ash