Reputation: 348
I try to get something like this from a MySQL-database via PHP and PDO query:
return array(
"Jungle Book" => new Book("Jungle Book", "R. Kipling", "A classic book."),
"Moonwalker" => new Book("Moonwalker", "J. Walker", ""),
"PHP for Dummies" => new Book("PHP for Dummies", "Some Smart Guy", "")
);
Each row of the database should be stored in an object. Can anyone help me with this?
I tried this:
return array(
foreach ($dbh->query("SELECT * FROM books") as $row) {
$row['name'] => new Book($row['name'], $row['author'], $row['description']);
}
)
...but foreach isn't allowed in arrays...
Background: for learning purposes I'm following this tutorial: http://php-html.net/tutorials/model-view-controller-in-php/ and I'm trying now to replace the static list of books with code that is working with a real database.
Upvotes: 1
Views: 609
Reputation: 157960
This question has nothing to do with mvc or pdo actually, but rather with PHP syntax at all.
Your task is rather simple, only you need is to refrain from idea of having all the code in one single operator:
$data = array();
$stmt = $dbh->query("SELECT * FROM books");
foreach ($stmt->fetchAll() as $row) {
$data[$row['name']] = new Book($row['name'], $row['author'], $row['description']);
}
return $data;
Although PDO has a syntax sugar for you, in my opinion one have to learn the underlying basic statements first.
Upvotes: 3
Reputation: 562801
You can set the fetch type to FETCH_CLASS.
Creating and returning the array in a single statement is an artificial and needless requirement. I wouldn't do that, it makes one's code hard to debug, hard to test, and hard to maintain. Also the query() method may return false
on error, so it will be a fatal error if you try to use it in a foreach statement.
$stmt = $dbh->query("SELECT * FROM books");
if ($stmt === false) { /* do something to handle the error */ }
$results = $stmt->fetchAll(PDO::FETCH_CLASS, 'Book');
return $results;
Or if you want a results array indexed by name:
$stmt = $dbh->query("SELECT * FROM books");
if ($stmt === false) { /* do something to handle the error */ }
$results = array();
while ($book = $stmt->fetch(PDO::FETCH_CLASS, 'Book')) {
$results[$book->name] = $book;
}
return $results;
Upvotes: 3
Reputation: 9142
You're probably wanting to return associative array values. In your current code, you cannot run a foreach
while inside the array. But you can do this:
return $dbh->query("SELECT * FROM books")->fetchAll(PDO::FETCH_ASSOC);
Upvotes: 0