Attis
Attis

Reputation: 124

PDO/MySQL fetch multiple columns with if statement

I'm currently trying to fetch two images location from my database, how do I return both columns and if both empty then echo another image. This is what I've got so far. How do I return both photo and photo_small so that I may echo them in a php file.

PUBLIC FUNCTION Profile_Pic($uiD) {
    $sth = $this->db->prepare("SELECT photo,photo_small FROM users WHERE uiD = :id");
    $sth->execute(array(':id' => $uiD));

        if ($sth->rowCount() > 0) {
                $data = $row['photo'];
            return $data; 
        } else {
            $data = './icons/users.png';
            return $data;
        } 
    }

Upvotes: 0

Views: 2126

Answers (2)

Your Common Sense
Your Common Sense

Reputation: 157895

PUBLIC FUNCTION Profile_Pic($uiD) {
    $sql = "SELECT photo,photo_small FROM users WHERE uiD = ?";
    $sth = $this->db->prepare($sql);
    $sth->execute(array($uiD));
    $data = $sth->fetch();
    if (empty($data['photo'])) {
        $data['photo'] = './icons/users.png';
    }
    if (empty($data['photo_small'])) {
        $data['photo_small'] = './icons/users.png';
    }
    return $data;
}

if you want to replace both images if even one is absent

PUBLIC FUNCTION Profile_Pic($uiD) {
    $sql = "SELECT photo,photo_small FROM users WHERE uiD = ?";
    $sth = $this->db->prepare($sql);
    $sth->execute(array($uiD));
    $data = $sth->fetch();
    if (empty($data['photo']) || empty($data['photo_small'])) {
        $data['photo'] = './icons/users.png';
        $data['photo_small'] = './icons/users.png';
    }
    return $data;
}

Upvotes: 3

Aiias
Aiias

Reputation: 4748

  1. Just return all of the values you want in an array.

  2. You can ensure that both photo and photo_small are not empty strings or NULL by using empty().

  3. Don't forget to retrieve your row using PDOStatement::fetch().

  4. You should not use rowCount() to determine the number of rows returned in a SELECT statement. According to the documentation for PDOStatement::rowCount():

    For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement.

Try this:

$row = $sth->fetch(PDO::FETCH_ASSOC);
if ($row && !empty($row['photo']) && !empty($row['photo_small'])) {
  $data = array('photo' => $row['photo'], 'photo_small' => $row['photo_small']);
  return $data; 
} else {
  $data = array('photo' => './icons/users.png', 'photo_small' => './icons/users.png');
  return $data;
} 

Then when you call the function, your returned result can be used like this:

$uiD = 1;
$result = Profile_Pic($uiD);
$photo = $result['photo'];
$photo_small = $result['photo_small'];

Upvotes: 0

Related Questions