Undefined index: stream

Asked

Viewed 121 times

0

I am studying php and can not understand the reason for this error. It executes the code as it should until a certain part. Basically I’m trying to use a database where users will insert Twitch nicknames (everything working ok so far) and from that database this script will check if they are online (in case the script below)If they are, they’ll display a preview along with the title. But it displays the error and does not load the other streams into the database, only 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>";
}
}
?>

1 answer

1

This is one of the most common warnings for those who are starting, basically it serves to warn you that somewhere in your code you are trying to access an index of an array that has not been set.

When you access an index of a vector and cannot guarantee that it exists, choose to use the function isset, returning true whether the parameter passed has been previously defined and false otherwise.

It would look something like this in your case

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.