How to display image BLOB from MySQL with PHP?

Spread the love

Sometimes, we want to display image BLOB from MySQL with PHP.

In this article, we’ll look at how to display image BLOB from MySQL with PHP.

How to display image BLOB from MySQL with PHP?

To display image BLOB from MySQL with PHP, we can call a few functions.

To insert a file into the database, we write

$db = new mysqli("localhost", "root", "", "DbName");
$image = file_get_contents($_FILES["images"]["tmp_name"]);
$query = "INSERT INTO products (image) VALUES(?)";
$stmt = $db->prepare($query);
$stmt->bind_param("s", $image);
$stmt->execute();

to call file_get_contents to get the file from the $_FILES array.

Anbd then we call bind-param with 's' and $image to bind theparameter to the $query.

And then we call execute to run the query.

Next, we get the file and display it with

$db = new mysqli("localhost", "root", "", "DbName");
$sql = "SELECT * FROM products WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param("s", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_array();
echo '<img src="data:image/jpeg;base64,' . base64_encode($row["image"]) . '"/>';

We make a query to get the file with prepare, bind_param, and execute.

And then we call get_result and fetch_array to get the result data as an associative array.

Finally, we display the image after calling base64_encode with the returned image to convert it to base64 string.

Then we use that has the src attribute value for the img element.

Conclusion

To display image BLOB from MySQL with PHP, we can call a few functions.

Leave a Reply

Your email address will not be published. Required fields are marked *