0

I have this code trying to create a json file from sql database. the code prints out FINE but it is giving a warning saying

Warning: Creating default object from empty value in C:\xampp\htdocs\z\index.php on line 5

can any on fix the error for me. here is my code.

 <?php include '../config.php';
 $sth = mysqli_query($conn,"SELECT * from movies limit 4");

 while($r = mysqli_fetch_assoc($sth)) {
     $rows->id = $r['id'];
     $rows->hidy = $r['hidy'];
 }

 print json_encode($rows);
treyBake
  • 6,440
  • 6
  • 26
  • 57
  • 3
    it would mean $rows isn't defined - it's not an error, it's a warning. – treyBake May 13 '19 at 09:41
  • Have you tied to research this, there are multiple answers regarding this such as ; https://stackoverflow.com/questions/8900701/creating-default-object-from-empty-value-in-php – Will May 13 '19 at 09:42
  • Have you thought of using `mysqli_fetch_object()` instead? (as well as only fetching columns you want to output) – Nigel Ren May 13 '19 at 09:42
  • 1
    Possible duplicate of [Creating default object from empty value in PHP?](https://stackoverflow.com/questions/8900701/creating-default-object-from-empty-value-in-php) – Will May 13 '19 at 09:42
  • Why don't you just do the one-liner `json_encode(mysqli_fetch_all($sth, MYSQLI_ASSOC))`? Should achieve the same result. – apokryfos May 13 '19 at 09:43

1 Answers1

0

You need to create a new class for the properties to exist in. The simple way is to use strClass().

Also as you are in a loop of possibly 4 result rows, the loop needs to save the data in an array or you will lose results 1,2,3 and only have result 4 shown in the JSON

<?php 
include '../config.php';
$sth = mysqli_query($conn,"SELECT * from movies limit 4");

$rows = array();

while($r = mysqli_fetch_assoc($sth)) {
    $obj        = new stdClass();      // new line
    $obj->id    = $r['id'];
    $obj->hidy  = $r['hidy'];
    // you are in a loop of 4 results, so need an array of results
    $rows[] = $obj;
}
echo json_encode($rows);

Or, select only the columns you want to use and fetch the results as an object ->fetch_object()

<?php 
include '../config.php';
$sth = mysqli_query($conn,"SELECT id,hidy from movies limit 4");

$rows = array();

while($r = $sth->fetch_object()) {
    $rows[] = $r;
}
echo json_encode($rows);
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149