简体   繁体   English

查询无法保存

[英]Query won't save

I made this query to show me the 'rank' of the Result ordered by there points. 我进行了此查询,以显示按点排序的结果的“排名”。 The query works fine but for some reason, I did not get any results whent trying to fetch it with php Maybe someone can tell me why? 该查询工作正常,但由于某些原因,当尝试使用php进行获取时,我没有得到任何结果。也许有人可以告诉我为什么?

(int) $a    = $_GET['a'];
if($ranking = $con->prepare("SET @rownum := 0; SELECT rank, id FROM (SELECT @rownum := @rownum + 1 AS rank, id FROM anime ORDER BY points DESC) as result WHERE id=$a"))
{
    $ranking->execute();
    $ranking->next_result();
    $ranking->bind_result($rank, $id);

    while($ranking->fetch()) 
    {
        var_dump($rank, $id);
        if($id == $a)
        {
          echo "<span class='rnknr'>#$rank</span>";
        }
    }

    $ranking->close();
}

} }

$ranking->execute(); $ ranking-> execute(); may return multiple resultsets if query contains more than 1 expression. 如果查询包含多个表达式,则可能返回多个结果集。

Try this 尝试这个

(int) $a    = $_GET['a'];
if($ranking = $con->prepare("SET @rownum := 0; SELECT rank, id FROM (SELECT @rownum := @rownum + 1 AS rank, id FROM anime ORDER BY points DESC) as result WHERE id=1"))
{
    $ranking->execute();
    $ranking->next_result(); //<- advance to the result set for 2nd query (The select query)
    $ranking->bind_result($rank, $id);

    while($ranking->fetch()) 
    {
    if($id == $a)
        {
          echo "<span class='rnknr'>#$rank</span>";
        }
    }

    $ranking->close();
}

You have 2 queries in your statement so only calling fetch will give you the result of the first query SET @rownum := 0 . 您的语句中有2个查询,因此只有调用fetch才能给您第一个查询SET @rownum := 0 You need to advance to the 2nd result set by calling next_result 您需要通过调用next_result进入第二个结果集

You must use some special method from mysqli::multi_query because this is multi query :) Now your code could look like this: 您必须使用mysqli :: multi_query的一些特殊方法,因为这是多重查询:)现在您的代码可能如下所示:


$mysqli = mysqli_connect(HOST, USER, PASS, DB);

#(int) $a = $_GET['a']; -> What is this ?

$a = (int)$_GET['a']; //This is simplest casting

$sql = 'SET @rownum := 0; SELECT rank, id FROM (SELECT @rownum := @rownum + 1 AS rank, id FROM anime ORDER BY points DESC) as result WHERE id='.$a;
if ($mysqli->multi_query($sql)) {
    $mysqli->next_result();
    $result = $mysqli->store_result();
    while ($row = $result->fetch_assoc()) {
        if($row['id'] == $a)
        {
          echo "rank: #{$row['rank']}";
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM