Admee
Admee

Reputation: 3

How to avoid notice undefined index when accessing array by key

<?php

    $hostname='localhost';
    $username='root';
    $password='';
    $database='jsondb';

    $conn=mysqli_connect($hostname,$username,$password,$database) or die ('Connecting to Mysql failed');

     $jsonCont = file_get_contents('https://graph.facebook.com/186622721684184?fields=posts{id,full_picture,created_time,from,message}&access_token=');

     $content = json_decode($jsonCont, true);
     for($x = 0; $x <= 24; $x++){

     $id = $content['posts']['data'][$x]['id'];
     $message = $content['posts']['data'][$x]['message'];
     $name = $content['posts']['data'][$x]['from']['name'];
     $full_picture = $content['posts']['data'][$x]['full_picture'];
     $created_time = $content['posts']['data'][$x]['created_time'];

    mysqli_query($conn,"insert into fbjsontable value('$id', '$message', '$name', '$full_picture', '$created_time')");
    }

?>

this is my full code. im using fb graph data. when i post json data from graph to database, Notice: Undefined index: full_picture in C:\xampp\htdocs\event&happening\jsonCon.php on line 21 this message will be present because the full_pictures doesn't exist. How to ignore the not exist column?

Upvotes: 0

Views: 608

Answers (2)

Jimmmy
Jimmmy

Reputation: 579

if you use php7.0+ you can avoid notice by ternary operator like this:

$full_picture = $content['posts']['data'][$x]['full_picture'] ?? null;

$full_picture will now contain sent data or null when data was not received.

Upvotes: 1

pr1nc3
pr1nc3

Reputation: 8338

First of all make sure your db field can accept null or empty values. After that you can go like this :

isset($content['posts']['data'][$x]['full_picture'])?$fullpicture=$content['posts']['data'][$x]['full_picture']:$fullpicture='';

This line of code checks if the image exists and if it does it will assign it's value to your variable $fullpicture or else will leave the variable empty.

The error is coming from the fact that your $fullpicture variable has not assigned with any value. As i said though make sure your db-field accepts empty field. If not and you don't have control over your table then go for something like:

isset($content['posts']['data'][$x]['full_picture'])?$fullpicture=$content['posts']['data'][$x]['full_picture']:$fullpicture='Image not found';

Upvotes: 0

Related Questions