Fatal error: Call to a member function fetch_assoc

2019-07-09 01:49发布

I tried to execute a query and iterate thru the result. The echo "<h1>" . $row["SummonerId"]. "</h1>"; works and it print it out at the page. But somehow this Error occurred after the printed result:

Fatal error: Call to a member function fetch_assoc() on string

I saw many errors similar to this. But those are on a non-object and not on string. What is that error?

Here is my code:

$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();

标签: php mysqli
1条回答
Root(大扎)
2楼-- · 2019-07-09 02:34

$result variable is used to loop thru mysql query, you have to use different variable names inside your loop

$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();

One more little thing I noticed.. $resultJSON and $resultJSON_decoded doesn't match inside the loop

查看更多
登录 后发表回答