我目前正在尝试从我的数据库中获取两个图像位置,如何返回两列,如果两个列都为空,则回显另一个图像。这是我到目前为止所得到的。 如何返回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;
}
}
答案 0 :(得分: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;
}
答案 1 :(得分:0)
empty()
确保photo
和photo_small
不是空字符串或NULL
。PDOStatement::fetch()
检索您的行。您不应使用rowCount()
来确定SELECT
语句中返回的行数。根据{{3}}的文档:
对于大多数数据库,PDOStatement :: rowCount()不返回受SELECT语句影响的行数。
试试这个:
$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;
}
然后当您调用该函数时,您返回的结果可以像这样使用:
$uiD = 1;
$result = Profile_Pic($uiD);
$photo = $result['photo'];
$photo_small = $result['photo_small'];