Can you provide an example of how to integrate a PHP script into an HTML img tag to display an image stored in a database?
To display an image stored in a database using a PHP script, you can retrieve the image data from the database and then use base64 encoding to embed it into an HTML img tag. This allows you to display the image directly on a webpage without needing to store the image file on the server.
<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');
// Retrieve image data from the database
$stmt = $pdo->prepare("SELECT image_data FROM images WHERE id = :id");
$stmt->bindParam(':id', $imageId);
$stmt->execute();
$imageData = $stmt->fetchColumn();
// Display the image using base64 encoding
echo '<img src="data:image/jpeg;base64,'.base64_encode($imageData).'" />';
?>
Keywords
Related Questions
- How can AJAX be utilized to enhance the functionality of automatically displaying associated values in PHP after selection in a dropdown?
- How can the use of GET requests in PHP be optimized to prevent unintended code execution?
- What are the potential pitfalls of using PHP frameworks, especially for beginners?