从MySQL自动填充stdClass

时间:2017-11-12 02:55:37

标签: php

我正在使用stdClass创建一个类,我想自动添加所有列数据。目前,我正在函数中执行以下操作...

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.......

这工作正常,但如果我有一天在课程表中添加一个新列(让我们说“描述”),我会喜欢这些信息。自动添加到我的stdClass,而不必返回并手动将其添加为此功能中的新行。

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:0)

对于那些感兴趣的人," foreaching"通过MySQL返回的对象是可行的方法(信用到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;          
    }

希望它有所帮助。