2016-04-25 105 views
2

我嘗試執行查詢並遍歷結果。 echo "<h1>" . $row["SummonerId"]. "</h1>";的作品,它在頁面上打印出來。但不知怎的,這個錯誤發生在打印結果後:致命錯誤:調用字符串上的成員函數fetch_assoc()

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

我看到了很多類似這樣的錯誤。但那些是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(); 
+0

字符串是非對象。 – AbraCadaver

+0

在你的問題的代碼中,'$ row [「SummonerId」]'輸出後''fetch_assoc()'不被使用,'$ result'不能是一個字符串,所以它似乎不可能產生這個特定的錯誤。是否有更多的代碼不包括在內? –

+0

是的,我不知道這可能是如何產生這個錯誤。 – VikingBlooded

回答

4

$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在循環內部不匹配

相關問題