I'm not sure if this is even possible after trying to figure it out for hours but here goes...
I have an class, UserPicture, which has properties for filename, filetype, created etc. (i.e. it doesn't store the actual picture as a blob, rather references it by using $filename.$filetype).
I want to be able to have a page that displays all of a user's pictures, so I need to retrieve all rows from the DB relevant to that user. I've got the associative array out of the DB successfully and have used the following code to create the object, which works as I have tested the output of it by echoing it...
$result=query("SELECT * FROM pictures WHERE user_id=$user_id");
// Returns associative array with numerous succesfully.
$pictures = array();
foreach($result as $row) {
$pictures = new UserPicture($row);
}
This kinda works but I only get the last row as an object in the array. So I have tried array_push...
foreach($result as $row) {
array_push($pictures, new UserPicture($row));
}
...and I've tried using $pictures[]=new UserPicture(开发者_Python百科$row), but both just give me the following error...
Catchable fatal error: Object of class UserPicture could not be converted to string in user_picture_manage.php on line 72
If anyone could please shed any light on what I'm doing wrong that would be very helpful!
Many thanks, Steve
You're overwriting the $pictures
variable in your above code. You need to add a new key for each row. The following should do the trick:
$result=query("SELECT * FROM pictures WHERE user_id=$user_id");
// Returns associative array with numerous succesfully.
$pictures = array();
foreach($result as $row) {
$pictures[] = new UserPicture($row);
}
Note where I've added squared braces ([]
). For each iteration in the foreach
loop, a new key will be added to the $pictures
array containing the new UserPicture
class as the value.
You should then be able to iterate over your new $pictures
array as follows:
foreach ($pictures as $picture) {
$src = $picture->filename . "." . $picture->filetype;
echo '<img src="<?php echo $src; ?>" alt="" />';
}
精彩评论