The benefit of using fetchColumn()
is that it returns a single value. This can slightly simplify your code by removing the necessity to reference an array key if you only need the value from one column. It isn't working because you're using $row["profile_pic"]
and $row
is not an array.
If you're going to use fetchColumn()
, you need to do one of two things:
-
Modify your query so that it only fetches the column you want,
rather than using *
. Then your code will need to be
$query = $db->query("SELECT profile_pic from members...");
$src = $query->fetchColumn();
if ($src) {
echo '<img width="100" height="100" src="'.$src.'"/>';
-
Add a number to fetchColumn()
that indicates which column you want
to fetch. Then your code will need to be
$query = $db->query("SELECT * from members...");
$src = $query->fetchColumn(4);
// or whatever the numeric index of the column you want is
if ($src) {
echo '<img width="100" height="100" src="'.$src.'"/>';
Either of these should work. But I should also mention that if you want to use any other columns from your query, you should NOT use fetchColumn()
, because once you have done this, you will not be able to access any other columns from that row of your query result. If this is the case, you can change your fetch from
$row = $query->fetchColumn();
to
$row = $query->fetch(PDO::FETCH_ASSOC);
Then you will still be able to get other columns from the row, and you can still use $row["profile_pic"]
as you do in your original code.
To address your comment, the way I would suggest doing this in order to display a default image if there isn't one in your database is to set $src
to the default image path if it is empty, like this:
$src = $query->fetchColumn();
if (!$src) {
$src = 'default_image.png'; // or whatever the path/filename is
}
echo '<img width="100" height="100" src="'.$src.'"/>';