致命错误:在字符串上调用成员函数fetch_assoc()

时间:2016-04-25 19:59:48

标签: php mysqli

我尝试执行查询并通过结果进行迭代。 echo "<h1>" . $row["SummonerId"]. "</h1>";有效,并在页面上打印出来。但不知何故,这个错误发生在打印结果之后:

  

致命错误:在字符串

上调用成员函数fetch_assoc()

我看到很多类似的错误。但这些是on a non-object而不是on string。那是什么错误?

这是我的代码:

$servername = "localhost:3307";
$username = "root";
$password = "";
$dbname = "st-datacollector";

$conn = new mysqli($servername, $username, $password, $dbname);

$sql = "SELECT * FROM summoner";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "<h1>" . $row["SummonerId"]. "</h1>";  
        $summonerId = $row["SummonerId"];
        $url = "https://euw.api.pvp.net/api/lol/euw/v1.3/game/by-summoner/" . $summonerId . "/recent?api_key=" . $api_key;

        $result = file_get_contents($url);
        $resultJSON = json_decode($result);


        foreach($resultJSON_decoded->games as $game){
            echo $game->gameMode." ".$game->gameType." ".$game->subType;
            echo "<br>";
        }           
    }
} else {
    echo "0 results";
}

$conn->close();

1 个答案:

答案 0 :(得分:5)

$result变量用于循环通过mysql查询,你必须在循环中使用不同的变量名

$servername = "localhost:3307";
$username = "root";
$password = "";
$dbname = "st-datacollector";

$conn = new mysqli($servername, $username, $password, $dbname);

$sql = "SELECT * FROM summoner";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "<h1>" . $row["SummonerId"]. "</h1>";  
        $summonerId = $row["SummonerId"];
        $url = "https://euw.api.pvp.net/api/lol/euw/v1.3/game/by-summoner/" . $summonerId . "/recent?api_key=" . $api_key;

        $fcontents = file_get_contents($url);
        $resultJSON = json_decode($fcontents);

        foreach($resultJSON_decoded->games as $game){
            echo $game->gameMode." ".$game->gameType." ".$game->subType;
            echo "<br>";
        }           
    }
} else {
    echo "0 results";
}

$conn->close();

我注意到的另一件小事...... $resultJSON$resultJSON_decoded在循环内部不匹配