0

I'm using stdClass to create a class and I'd like to add all column data to it automatically. Currently, I'm doing the following from within a function...

function get_course_info($course_id){
   $course = new stdClass;

   //Add everything from the courses table to the "$course" class
   $query = $db->query("SELECT * FROM courses WHERE course_id = ?",array($course_id));
   $results = $query->first();

   $course->type = $results->type;
   $course->category = $results->category;
   $course->name = $results->name;
   etc.......

This is working fine, but if I someday add a new column to the courses table (let's say "description"), I'd like that info. to automatically be added to my stdClass without having to go back and manually add it in as a new line in this function.

Is there a way to do this?

gtilflm
  • 1,389
  • 1
  • 21
  • 51
  • Possibly duplicate of [this](https://stackoverflow.com/questions/4976624/looping-through-all-the-properties-of-object-php) – Stefan Nov 12 '17 at 03:04
  • 1
    Why don't you just use the object returned from the query? I.e. `$course = $query->first();` – Mischa Nov 12 '17 at 03:07
  • `SELECT *` is not something you want to use. You \want\ to update your function when your data changes because they should never be arbitrary. – Erik Nov 12 '17 at 03:45

1 Answers1

0

For those who are interested, "foreaching" through the object returned from MySQL was the way to go (credit to Mischa).

    //Add everything from the courses table to the "$course" class
    $query = $db->query("SELECT * FROM courses WHERE course_id = ?",array($course_id));
    $results = $query->first();

    foreach($results as $column => $value){
        $course->$column = $value;          
    }

Hope it helps someone.

gtilflm
  • 1,389
  • 1
  • 21
  • 51