-1

i have created an api to fetch data from database to echo it as json and finally display it in html but while echoing the data,

i am getting below php errors

Notice: Undefined offset: 80 in /opt/lampp/htdocs/ReadExchange/api.php on line 16

Notice: Undefined offset: 79 in /opt/lampp/htdocs/ReadExchange/api.php on line 16

Notice: Undefined offset: 78 in /opt/lampp/htdocs/ReadExchange/api.php on line 16

and so on,

PHP Code

$db_result_set = $db->prepare('SELECT p.Id, p.FirstName, p.MiddleName, p.LastName, p.Gender, p.Location, p.Email, p.Mobile,b.BookTitle, b.BookGenre, b.BookWriter, b.BookDescription FROM personaldetails AS p LEFT JOIN bookdetails AS b ON b.UserId = p.Id ORDER BY p.Id DESC');;

$db_result_set->execute();

$final = [];
foreach ($db_result_set as $u) {

    if (!is_array($final[$u["Id"]])) {   //line 16 
        $final[$u["Id"]]= [
            "Id" => $u["Id"],
            "FirstName" => $u["FirstName"],
            "MiddleName" => $u["MiddleName"],
            "LastName" => $u["LastName"],
            "Gender" => $u["Gender"],
            "Location" => $u["Location"],
            "Email" => $u["Email"],
            "Mobile" => $u["Mobile"],
         ];
    }
    $final[$u["Id"]]["books"][] = [
        "BookTitle" => $u["BookTitle"],
        "BookGenre" => $u["BookGenre"],
        "BookWriter" => $u["BookWriter"],
        "BookDescription" => $u["BookDescription"],
    ];

}   
    
    header('Content-type: application/javascript');
    echo json_encode($final);
    

?>

i am not confirm but i think because of this i am not getting json data in html.

Community
  • 1
  • 1
Ranjank
  • 133
  • 1
  • 14
  • Use `if (!empty($final[$u["Id"]]))` – RJParikh Jun 02 '16 at 08:03
  • Possible duplicate of [Reference - What does this error mean in PHP?](http://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – Henders Jun 02 '16 at 08:20
  • `header('Content-type: application/javascript');` ? What are you trying to echo? Do you mean `header('Content-type: application/json');` ? – Raptor Jun 02 '16 at 08:42

2 Answers2

1

Not: if (!is_array($final[$u["Id"]]))

but: if (!isset($final[$u["Id"]]))

nospor
  • 4,190
  • 1
  • 16
  • 25
0

You are trying to check if an undefined offset exists in your array. You need to first need to check if the offset exists with isset.

So change your code to

if (isset($final[$u["Id"]]) && ! is_array($final[$u["Id"]))
Marwelln
  • 28,492
  • 21
  • 93
  • 117