0

Hi so I am attempting to return all the "people" from my database and then create an object of the "person" data, then at the end of each while loop add the person to the array. Outside of the while loop i am then encoding said array.

Below attached is my current code:

class person {
   public $firstName = "";
   public $lastName = "";
}

$people = array();
$result = mysqli_query($con,"SELECT * FROM People");

while($row = mysqli_fetch_array($result)) {
      $firstName=$row['firstName'];
      $lastName=$row['lastName'];

      $e = new Person();        
      $e->firstName  = $firstName;
      $e->lastName = $lastName;

      array_push($people, $e);
}

json_encode($people);

Many thanks

3
  • 2
    And are you having any particular problem? Commented Oct 27, 2014 at 19:03
  • What is your question, friend? Commented Oct 27, 2014 at 19:03
  • My question is why isn't the code above working i guess Commented Oct 27, 2014 at 21:49

2 Answers 2

1

There doesn't appear to be a question here, but perhaps mysqli_fetch_object would be more useful to you in this case.

Also, watch your naming. You've called your class "person" and instantiated it as "Person". PHP is rather flexible about case, but this could lead to issues later on in your program.

Lastly, json_encode just encodes an object. If you want to display the result or push it to the browser for consumption, you'll need to echo it out:

header('Content-Type: application/json');
echo json_encode($people);
Sign up to request clarification or add additional context in comments.

Comments

0

Use "mysqli_fetch_assoc" instead of "mysqli_fetch_array" if you want to use an associative approach.

class Person 
{
   public $firstName = null;
   public $lastName  = null;
}

$people = array();
$result = mysqli_query($con,"SELECT * FROM `People`");

while($row = mysqli_fetch_assoc($result)) {
      $e = new Person();        

      $e->firstName = $row['firstName'];
      $e->lastName  = $row['lastName'];   
}

json_encode($people);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.