08-23-2023, 07:54 PM
[Tut] PHP Upload Image to Database with MySql
<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2023/08/php-upload-image-to-database-with-mysql.jpg" width="550" height="320" title="" alt="" /></div><div><div class="modified-on" readability="7.047619047619"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on July 2nd, 2023.</div>
<p>Do you want to upload an image to the database? Most application services move the uploaded files to a directory and save their path to the database.</p>
<p>Earlier, we saw code for storing <a href="https://phppot.com/php/mysql-blob-using-php/">uploaded images to the database using MySQL BLOB</a> fields. BLOB(Binary Large Data Object) is one of the MySql data types. It can have the file binary data. MySQL supports four types of BLOB datatype as follows.<br /><a class="demo" href="https://phppot.com/demo/php-upload-image-to-database/">View demo</a></p>
<ol>
<li>TINYBLOB</li>
<li>BLOB</li>
<li>MEDIUMBLOB</li>
<li>LONGBLOB</li>
</ol>
<p>For this example, we created one of the above BLOB fields in a MySQL database to see how to upload an image. Added to that, this code will fetch and BLOB data from the database and display the image to the browser.</p>
<h2>Database script</h2>
<p>Before running this example, create the required database structure on your server.</p>
<pre class="prettyprint"><code class="language-sql">CREATE TABLE images ( id INT(11) AUTO_INCREMENT PRIMARY KEY, image LONGBLOB NOT NULL );
</code></pre>
<p><img decoding="async" loading="lazy" class="alignnone size-large wp-image-21415" src="https://phppot.com/wp-content/uploads/2023/06/php-upload-image-to-database-output-550x320.jpg" alt="php upload image to database output" width="550" height="320" srcset="https://phppot.com/wp-content/uploads/2023/06/php-upload-image-to-database-output-550x320.jpg 550w, https://phppot.com/wp-content/uploads/20...00x175.jpg 300w, https://phppot.com/wp-content/uploads/20...68x447.jpg 768w, https://phppot.com/wp-content/uploads/20...output.jpg 1200w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>HTML form with an image upload option</h2>
<p>This is a usual file upload form with a file input. This field restricts the file type to choose only the images using the <em>accept</em> attribute.</p>
<p>On submitting this form, the upload.php receives the posted file binary data on the server side.</p>
<pre class="prettyprint"><code class="language-php-template"><!DOCTYPE html>
<html> <head> <title>PHP - Upload image to database - Example</title> <link href="style.css" rel="stylesheet" type="text/css" /> <link href="form.css" rel="stylesheet" type="text/css" />
</head> <body> <div class="phppot-container"> <h1>Upload image to database:</h1> <form action="upload.php" method="post" enctype="multipart/form-data"> <div class="row"> <input type="file" name="image" accept="image/*"> <input type="submit" value="Upload"> </div> </form> <h2>Uploaded Image (Displayed from the database)</h2> </div>
</body> </html></code></pre>
<h2>Insert an image into the database using PHP and MySql</h2>
<p>This PHP script gets the chosen file data with the $_FILES array. This array contains the base name, temporary source path, type, and more details.</p>
<p>With these details, it performs the file upload to the database. The steps are as follows,</p>
<ol>
<li>Validate file array is not empty.</li>
<li>Retrieve the image file content using file_get_contents($_FILES[“image”][“tmp_name”]).</li>
<li>Prepare the insert and bind the image binary data to the query parameters.</li>
<li>Execute insert and get the database record id.</li>
</ol>
<pre class="prettyprint"><code class="language-php-template"><?php
// MySQL database connection settings
$servername = "localhost";
$username = "root";
$password = "admin123";
$dbname = "phppot_image_upload"; // Make connection
$conn = new mysqli($servername, $username, $password, $dbname); // Check connection and throw error if not available
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);
} // Check if an image file was uploaded
if (isset($_FILES["image"]) && $_FILES["image"]["error"] == 0) { $image = $_FILES['image']['tmp_name']; $imgContent = file_get_contents($image); // Insert image data into database as BLOB $sql = "INSERT INTO images(image) VALUES(?)"; $statement = $conn->prepare($sql); $statement->bind_param('s', $imgContent); $current_id = $statement->execute() or die("<b>Error:</b> Problem on Image Insert<br/>" . mysqli_connect_error()); if ($current_id) { echo "Image uploaded successfully."; } else { echo "Image upload failed, please try again."; }
} else { echo "Please select an image file to upload.";
} // Close the database connection
$conn->close();
</code></pre>
<h2>Fetch image BLOB from the database and display to UI</h2>
<p>This PHP code prepares a SELECT query to fetch the image BLOB. Using the image binary from the BLOB, it creates the data URL. It applies PHP base64 encoding on the image binary content.</p>
<p>This data URL is set as a source of an HTML image element below. This script shows the recently inserted image on the screen. We can also show an image gallery of all the BLOB images from the database.</p>
<pre class="prettyprint"><code class="language-php-template"><?php // Retrieve the uploaded image from the database $servername = "localhost"; $username = "root"; $password = ""; $dbname = "phppot_image_upload"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $result = $conn->query("SELECT image FROM images ORDER BY id DESC LIMIT 1"); if ($result && $result->num_rows > 0) { $row = $result->fetch_assoc(); $imageData = $row['image']; echo '<img src="data:image/jpeg;base64,' . base64_encode($imageData) . '" alt="Uploaded Image" style="max-width: 500px;">'; } else { echo 'No image uploaded yet.'; } $conn->close(); ?>
</code></pre>
<p><a class="demo" href="https://phppot.com/demo/php-upload-image-to-database/">View demo</a> <a class="download" href="https://phppot.com/downloads/php/php-upload-image-to-database.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/php-upload-image-to-database/#top" class="top">↑ Back to Top</a> </p>
</div>
https://www.sickgaming.net/blog/2023/06/...ith-mysql/
<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2023/08/php-upload-image-to-database-with-mysql.jpg" width="550" height="320" title="" alt="" /></div><div><div class="modified-on" readability="7.047619047619"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on July 2nd, 2023.</div>
<p>Do you want to upload an image to the database? Most application services move the uploaded files to a directory and save their path to the database.</p>
<p>Earlier, we saw code for storing <a href="https://phppot.com/php/mysql-blob-using-php/">uploaded images to the database using MySQL BLOB</a> fields. BLOB(Binary Large Data Object) is one of the MySql data types. It can have the file binary data. MySQL supports four types of BLOB datatype as follows.<br /><a class="demo" href="https://phppot.com/demo/php-upload-image-to-database/">View demo</a></p>
<ol>
<li>TINYBLOB</li>
<li>BLOB</li>
<li>MEDIUMBLOB</li>
<li>LONGBLOB</li>
</ol>
<p>For this example, we created one of the above BLOB fields in a MySQL database to see how to upload an image. Added to that, this code will fetch and BLOB data from the database and display the image to the browser.</p>
<h2>Database script</h2>
<p>Before running this example, create the required database structure on your server.</p>
<pre class="prettyprint"><code class="language-sql">CREATE TABLE images ( id INT(11) AUTO_INCREMENT PRIMARY KEY, image LONGBLOB NOT NULL );
</code></pre>
<p><img decoding="async" loading="lazy" class="alignnone size-large wp-image-21415" src="https://phppot.com/wp-content/uploads/2023/06/php-upload-image-to-database-output-550x320.jpg" alt="php upload image to database output" width="550" height="320" srcset="https://phppot.com/wp-content/uploads/2023/06/php-upload-image-to-database-output-550x320.jpg 550w, https://phppot.com/wp-content/uploads/20...00x175.jpg 300w, https://phppot.com/wp-content/uploads/20...68x447.jpg 768w, https://phppot.com/wp-content/uploads/20...output.jpg 1200w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>HTML form with an image upload option</h2>
<p>This is a usual file upload form with a file input. This field restricts the file type to choose only the images using the <em>accept</em> attribute.</p>
<p>On submitting this form, the upload.php receives the posted file binary data on the server side.</p>
<pre class="prettyprint"><code class="language-php-template"><!DOCTYPE html>
<html> <head> <title>PHP - Upload image to database - Example</title> <link href="style.css" rel="stylesheet" type="text/css" /> <link href="form.css" rel="stylesheet" type="text/css" />
</head> <body> <div class="phppot-container"> <h1>Upload image to database:</h1> <form action="upload.php" method="post" enctype="multipart/form-data"> <div class="row"> <input type="file" name="image" accept="image/*"> <input type="submit" value="Upload"> </div> </form> <h2>Uploaded Image (Displayed from the database)</h2> </div>
</body> </html></code></pre>
<h2>Insert an image into the database using PHP and MySql</h2>
<p>This PHP script gets the chosen file data with the $_FILES array. This array contains the base name, temporary source path, type, and more details.</p>
<p>With these details, it performs the file upload to the database. The steps are as follows,</p>
<ol>
<li>Validate file array is not empty.</li>
<li>Retrieve the image file content using file_get_contents($_FILES[“image”][“tmp_name”]).</li>
<li>Prepare the insert and bind the image binary data to the query parameters.</li>
<li>Execute insert and get the database record id.</li>
</ol>
<pre class="prettyprint"><code class="language-php-template"><?php
// MySQL database connection settings
$servername = "localhost";
$username = "root";
$password = "admin123";
$dbname = "phppot_image_upload"; // Make connection
$conn = new mysqli($servername, $username, $password, $dbname); // Check connection and throw error if not available
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);
} // Check if an image file was uploaded
if (isset($_FILES["image"]) && $_FILES["image"]["error"] == 0) { $image = $_FILES['image']['tmp_name']; $imgContent = file_get_contents($image); // Insert image data into database as BLOB $sql = "INSERT INTO images(image) VALUES(?)"; $statement = $conn->prepare($sql); $statement->bind_param('s', $imgContent); $current_id = $statement->execute() or die("<b>Error:</b> Problem on Image Insert<br/>" . mysqli_connect_error()); if ($current_id) { echo "Image uploaded successfully."; } else { echo "Image upload failed, please try again."; }
} else { echo "Please select an image file to upload.";
} // Close the database connection
$conn->close();
</code></pre>
<h2>Fetch image BLOB from the database and display to UI</h2>
<p>This PHP code prepares a SELECT query to fetch the image BLOB. Using the image binary from the BLOB, it creates the data URL. It applies PHP base64 encoding on the image binary content.</p>
<p>This data URL is set as a source of an HTML image element below. This script shows the recently inserted image on the screen. We can also show an image gallery of all the BLOB images from the database.</p>
<pre class="prettyprint"><code class="language-php-template"><?php // Retrieve the uploaded image from the database $servername = "localhost"; $username = "root"; $password = ""; $dbname = "phppot_image_upload"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $result = $conn->query("SELECT image FROM images ORDER BY id DESC LIMIT 1"); if ($result && $result->num_rows > 0) { $row = $result->fetch_assoc(); $imageData = $row['image']; echo '<img src="data:image/jpeg;base64,' . base64_encode($imageData) . '" alt="Uploaded Image" style="max-width: 500px;">'; } else { echo 'No image uploaded yet.'; } $conn->close(); ?>
</code></pre>
<p><a class="demo" href="https://phppot.com/demo/php-upload-image-to-database/">View demo</a> <a class="download" href="https://phppot.com/downloads/php/php-upload-image-to-database.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/php-upload-image-to-database/#top" class="top">↑ Back to Top</a> </p>
</div>
https://www.sickgaming.net/blog/2023/06/...ith-mysql/