0

我目前正在尝试从我的数据库中获取两个图像位置,如何返回两个列,如果两个列都为空,则回显另一个图像。这就是我到目前为止所得到的。如何返回 photo 和 photo_small 以便我可以在 php 文件中回显它们。

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;
        } 
    }
4

2 回答 2

3
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;
}

如果您想替换两张图片(即使一张图片都不存在)

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;
}
于 2013-06-07T05:50:20.947 回答
0
  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'];
于 2013-06-07T05:38:42.670 回答