I am trying to fetch multiple rows into instances while passing an argument to the constructor(the PDO connection). I could fetch one row at a time and then construct them but I am looking for a one line solution.
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();
}
}
What about:
FETCH_INTOis used for adding data into an already existing class, so in your case usingFETCH_CLASSmakes more sense.Side note: Since you are already using PDO, you might as well take advantage of prepared statements. This provides the benefit of not having to worry about SQL injections.
The only thing in your code that would change is: