试图在sql查询中获取非对象的属性

时间:2017-10-30 15:01:14

标签: php mysql

我有以下SQL查询:

SET @rank=0; SELECT receivedData.* FROM (SELECT @rank:=@rank+1 AS rank, ID FROM data ORDER BY Eindtijd ASC) AS receivedData ORDER BY ID DESC LIMIT 1;

当我在我的服务器上运行phpmyadmin时,一切正常。

但是当我用php运行它时,我收到以下错误:

  

您的SQL语法有错误;查看与您的MySQL服务器版本相对应的手册,以便在'SELECT receivedData。* FROM(SELECT @rank:= @ rank + 1 AS rank,ID FROM FROM ORDER BY'在第1行附近)使用正确的语法

$sql2 = "SET @rank=0; SELECT receivedData.* FROM (SELECT @rank:=@rank+1 AS rank, ID FROM data ORDER BY Eindtijd ASC) AS receivedData ORDER BY ID DESC LIMIT 1;";
 $result = $conn->query($sql2) or die($conn->error);

我真的不明白为什么它在php中不起作用

3 个答案:

答案 0 :(得分:3)

帕特里克建议你可以试试:

$sSQL = "SET @rank=0;";

if($conn->query($sSQL)){
    $sSQL = "SELECT receivedData.* FROM (SELECT @rank:=@rank+1 AS rank, ID FROM data ORDER BY Eindtijd ASC) AS receivedData ORDER BY ID DESC LIMIT 1;";
    $conn->query($sSQL);
}

$conn->query()一次只能执行一个命令。来自手册: " PDO :: query()在单个函数调用中执行SQL语句,将语句返回的结果集(如果有)作为PDOStatement对象返回。"

因为您正在重用连接,所以查询仍然可以访问本地var。

答案 1 :(得分:1)

您可以合并这两个查询。

SET @rank=0;
SELECT
  receivedData.*
FROM (
  SELECT
     @rank := @rank + 1 AS rank
    , ID
  FROM
   data
  ORDER BY
   Eindtijd ASC
 )
   AS receivedData
 ORDER BY ID DESC LIMIT 1;

进入

SELECT
  receivedData.*
FROM (
  SELECT
     @rank := @rank + 1 AS rank
    , ID
  FROM
   data
  CROSS JOIN (SELECT @rank := 0) as init_user_param
  ORDER BY
   Eindtijd ASC
 )
   AS receivedData
 ORDER BY ID DESC LIMIT 1;

答案 2 :(得分:1)

使用PDO,您可以执行此操作:

$db = new PDO('mysql:host=127.0.0.1;dbname=test', 'root', 'password');

$statement = $db->prepare('SET @rank = "1";  SELECT receivedData.* FROM (SELECT @rank:=@rank+1 AS rank, ID FROM data ORDER BY Eindtijd ASC) AS receivedData ORDER BY ID DESC LIMIT 1;');

$statement->execute();

do {
    $data = $statement->fetchAll(\PDO::FETCH_ASSOC);
    var_dump($data);

} while ($statement->nextRowset());

第一个返回的数组将为空,因为第一个查询没有任何内容可以返回。第二个返回的数组将保存您的数据。