Undefined index: stream

0

I'm studying php and I can not understand the reason for this error. It runs the code as it should to some extent. Basically I am trying to use a database where users will enter the twitch nicks (everything working ok so far) and from that database this script will check if they are online (in the case the script below), if they are gone display a preview along with the title. However it displays the error and does not load the other streams into the bank, just the first.

  

Notice: Undefined index: stream in   C: \ xampp \ htdocs \ sc2streams \ online.php on line 22

<?php
include('connect.php');
$resultado = mysqli_query($conecta, "select * from streams");
$name = mysqli_fetch_assoc($resultado);
foreach ($name as $name) {
$streamsApi = 'https://api.twitch.tv/kraken/streams/';
$clientId = 'MinhaClientID';
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_HTTPHEADER => array(
'Client-ID: ' . $clientId
),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $streamsApi . $name
));

$response = curl_exec($ch);
echo curl_error($ch);
curl_close($ch);

$json = json_decode($response, true);
if ($json['stream'] != ""){
echo "<div class='stream-div'><div class='container'>";
echo "<a href='" .$json['stream']['channel']['url']."'>"."<img src='".$json['stream']['preview']['medium']."' height='180' width='300'/></a><br>";
echo "<p>".$json['stream']['channel']['status']." - Jogando - ".$json['stream']['game']."</p><br>";
echo "</div></div>";
}
}
?>
    
asked by anonymous 08.11.2016 / 21:13

1 answer

1

This is one of the most common warnings to beginners, basically it is to warn you that somewhere in your code you are trying to access an index of a vector that has not been defined.

When you access an index from a vector and can not guarantee that it exists, choose to use the isset function, which returns true if the passed parameter was previously set and false otherwise.

It would look more like that in your case

if (isset($json['stream']) && $json['stream'] != "") {
    //seu comando
}

Remembering that since you used the & & operator, if the first condition is false the second is not tested, which avoids notice

    
08.11.2016 / 22:25