Jeewantha Lahiru
Jeewantha Lahiru

Reputation: 394

How do I add a picture as a background-image property from sql databese which is saved as a longblob file?

I have created an authentication system using php, html and css. I am sending the profile pictures related each profile to sql database as longblob files using the code below.

<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="POST" enctype="multipart/form-data">
    <input type="file" name="profile_picture" id=""><br>
    <input type="submit" value="Update" name="profile_pic_update">
</form>
<?php
if($_SERVER["REQUEST_METHOD"]=="POST" && isset($_REQUEST["profile_pic_update"])){
     try{
         $pdo = new PDO("mysql:host=localhost;dbname=shoppingcart","root","");
         $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     }catch(PDOException $e){
         die("Error");
     }     

     $profile_picture_name = $_FILES["profile_picture"]["name"];
     $profile_picture_type = $_FILES["profile_picture"]["type"];
     $profile_picture_data = file_get_contents($_FILES["profile_picture"]["tmp_name"]);
     $sql = "INSERT INTO `profilepictures`(`name`, `mime`, `data`, `ownerId`) VALUES ($profile_picture_name,$profile_picture_type,$profile_picture_data, $_SESSION['id'])";
     $stmt = $pdo->prepare($sql);
     $stmt->execute();
}
?>

I can get an image from sql database to the img property using this code,

<?php
     $sql2 = "SELECT * FROM profilepictures WHERE ownerid=:ownerid";
     if($stmt2 = $pdo->prepare($sql2)){
          $stmt2->bindParam(":ownerid",$_SESSION["id"]);
          $stmt2->execute();
          if($stmt2->rowCount()==1){
               $row = $stmt2->fetch();
               echo "<img src='data:".$row['mime'].";base64,".base64_encode($row['data'])."'>";
          }
     }
?>

but the thing is I need to get this image as a background-image property of css.I have a resized div tag and I need that image as this div tag's background image. if I say simply, I need to use this as below,

<div class="profilePicture" style="background-image: url();">
</div>

How can I add the image to that background-image as a url?

Upvotes: 0

Views: 693

Answers (1)

Robin Gillitzer
Robin Gillitzer

Reputation: 1612

You can do this the same way as the img tag:

<div class="profilePicture" style="background-image: url('<?= "data:" . $row['mime'] . ";base64," . base64_encode($row['data']); ?>');">
</div>

Upvotes: 2

Related Questions