Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

mysqli

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();
like image 698
Phong6698 Avatar asked Feb 07 '23 04:02

Phong6698


1 Answers

$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

like image 170
Seva Kalashnikov Avatar answered Feb 10 '23 11:02

Seva Kalashnikov