PDO / MySQL使用if语句获取多个列

时间:2013-06-07 05:29:51

标签: php mysql if-statement pdo

我目前正在尝试从我的数据库中获取两个图像位置,如何返回两列,如果两个列都为空,则回显另一个图像。这是我到目前为止所得到的。 如何返回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;
        } 
    }

2 个答案:

答案 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)

  1. 只需返回数组中所需的所有值。
  2. 您可以使用empty()确保photophoto_small不是空字符串或NULL
  3. 请勿忘记使用PDOStatement::fetch()检索您的行。
  4. 您不应使用rowCount()来确定SELECT语句中返回的行数。根据{{​​3}}的文档:

      

    对于大多数数据库,PDOStatement :: rowCount()不返回受SELECT语句影响的行数。

  5. 试试这个:

    $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'];