dongmaoxi0477 2014-02-20 12:16
浏览 149
已采纳

PDO :: FETCH_OBJ +自定义类?

When I fetchAll() query results (SELECT * FROM users ...) as an array of objects, I want these objects to be of a certain class, namely User.

  1. How do I force PDO to use the data type User for the result objects, and
  2. do I have to define all member variables corresponding to the field names in the class?
  • 写回答

2条回答 默认 最新

  • duanouyong4228 2014-02-20 12:24
    关注

    there is a static field to tell PDO to fetch into a class, PDO::FETCH_CLASS.

    Here is an example of getting User objects;

    class User {
        public $name;
        public $firstname;
    }
    

    You have to ensure that the field names are same as the column ones and that the class is accessible from the class / file you're working from. (SELECT * works too, just have all fields available)

    $query = "SELECT name, firstname FROM users";
    

    And to wrap it in classes, use the next,

    $users = $sth->fetchAll(PDO::FETCH_CLASS, "User");
    

    Then you can simply access it as an array of User objects.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?