0

我试图在将参数传递给构造函数(PDO 连接)时将多行提取到实例中。我可以一次取一行然后构造它们,但我正在寻找一种单行解决方案。

class Member {

        // PDO connection
        public $conn;

        public $Members_ID;
        public $Members_FirstName;
        public $Members_LastName;


        function __construct($conn){         
            $this->conn= $conn;
        }


        // Returns an array of Members with the email address that is given
        // (Multiple members can have the same email)
        public static function getMembersFromEmailAddress($emailAddress, $conn){

            try 
            {
                $result = $conn->query("SELECT * FROM members WHERE Members_Email ='". $emailAddress ."'"); 

               //HERE I WANT MEMBERS TO BE AN ARRAY OF MEMBER OBJECTS
                $members = $result->fetch(PDO::FETCH_INTO, new Member($conn));
                return $members
            }
            catch(PDOException $e)
            {
                echo $e->getMessage();
            }

}
4

3 回答 3

3

关于什么:

$args= array();
$args[] = $conn;

$members = $result->fetchAll(PDO::FETCH_CLASS, 'Member', $args);

FETCH_INTO用于将数据添加到已经存在的类中,因此在您的情况下使用FETCH_CLASS更有意义。


旁注:由于您已经在使用 PDO,您不妨利用准备好的语句。这提供了不必担心 SQL 注入的好处。

您的代码中唯一会改变的是:

$stmt = $conn->prepare("SELECT * FROM members WHERE Members_Email = :member_email");
$result = $stmt->execute(array(":member_email" => $emailAddress));
于 2013-01-06T19:54:54.153 回答
0

你有一个设计缺陷。如果您使用的是非常小的应用程序,则必须由存储库/实体管理器或控制器触发查询。

$conn绝不是 的属性Member

如果它在控制器中,我会给你代码:

try{
    $s = $connection->prepare('SELECT * FROM members WHERE Members_Email=:mail');
    $s->execute(array('mail'=>$emailAddress));
    $result = $s->fetchAll(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE,Member);
}

PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE语句是一种确保在PDO 将数据放入对象之前调用构造函数的方法

于 2013-01-06T19:57:12.127 回答
0

在您的代码中,您仅将一行提取到一个对象中。

您需要循环获取,并添加到数组中:

while ($row = $result->fetch(PDO::FETCH_INTO, new Member($conn)) {
    $members[] = $row;
}
return $members;
于 2013-01-06T19:55:14.513 回答