Wednesday, August 29, 2018

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



I tried to execute a query and iterate thru the result. The echo "

" . $row["SummonerId"]. "

"; 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 "

" . $row["SummonerId"]. "

";
$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 "
";
}
}
} else {
echo "0 results";
}

$conn->close();

Answer




$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 "

" . $row["SummonerId"]. "

";
$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 "
";
}
}
} else {
echo "0 results";
}


$conn->close();


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


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...