PHP: Retrieve image from MySQL using PDO

后端 未结 4 1813
误落风尘
误落风尘 2020-12-06 22:38

I am refactoring some old code, including rewriting basic mysql queries to use PDO.

The following works brilliantly in all browsers and for all image types:

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-06 22:42

    You can use this code to get image from database using PDO:

    public function getImage($id){
        $sql = "SELECT * FROM images WHERE id = ?";
        $sth = $this->dbh->prepare($sql);
    
        $sth->bindParam(1,$id);
        $sth->execute();
    
    
        $num = $sth->rowCount();
        if( $num ){
            $row = $sth->fetch(PDO::FETCH_ASSOC);
            header("Content-type: ".$row['type']);
            print $row['image'];
            exit;
        }else{
            return null;
        }
    }
    

    type - data type(column name) such as image/png or image/gif
    image - image data(column name) stored in table as LOB
    $this->dbh connection handler
    It works for me but now I need to find out how to use it with JS because result of this function is passed to JavaScript code - so called ajax

提交回复
热议问题