我正在尝试将多个行提取到实例中,同时将参数传递给构造函数(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();
}
}
答案 0 :(得分:3)
怎么样:
$args= array();
$args[] = $conn;
$members = $result->fetchAll(PDO::FETCH_CLASS, 'Member', $args);
FETCH_INTO
用于将数据添加到已存在的类中,因此在您的情况下使用FETCH_CLASS
更有意义。
旁注:由于您已经在使用PDO,因此您也可以利用prepared statements。这提供了不必担心SQL注入的好处。
代码中唯一会改变的是:
$stmt = $conn->prepare("SELECT * FROM members WHERE Members_Email = :member_email");
$result = $stmt->execute(array(":member_email" => $emailAddress));
答案 1 :(得分:0)
在您的代码中,您只需将一行提取到一个对象中。
你需要获取一个循环,并添加到一个数组:
while ($row = $result->fetch(PDO::FETCH_INTO, new Member($conn)) {
$members[] = $row;
}
return $members;
答案 2 :(得分: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将数据放入对象之前将调用