Sick Gaming
[Tut] PHP Upload Image to Database with MySql - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Programming (https://www.sickgaming.net/forum-76.html)
+--- Forum: PHP Development (https://www.sickgaming.net/forum-82.html)
+--- Thread: [Tut] PHP Upload Image to Database with MySql (/thread-101284.html)



[Tut] PHP Upload Image to Database with MySql - xSicKxBot - 08-23-2023

[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/2023/06/php-upload-image-to-database-output-300x175.jpg 300w, https://phppot.com/wp-content/uploads/2023/06/php-upload-image-to-database-output-768x447.jpg 768w, https://phppot.com/wp-content/uploads/2023/06/php-upload-image-to-database-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">&lt;!DOCTYPE html&gt;
&lt;html&gt; &lt;head&gt; &lt;title&gt;PHP - Upload image to database - Example&lt;/title&gt; &lt;link href="style.css" rel="stylesheet" type="text/css" /&gt; &lt;link href="form.css" rel="stylesheet" type="text/css" /&gt;
&lt;/head&gt; &lt;body&gt; &lt;div class="phppot-container"&gt; &lt;h1&gt;Upload image to database:&lt;/h1&gt; &lt;form action="upload.php" method="post" enctype="multipart/form-data"&gt; &lt;div class="row"&gt; &lt;input type="file" name="image" accept="image/*"&gt; &lt;input type="submit" value="Upload"&gt; &lt;/div&gt; &lt;/form&gt; &lt;h2&gt;Uploaded Image (Displayed from the database)&lt;/h2&gt; &lt;/div&gt;
&lt;/body&gt; &lt;/html&gt;</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">&lt;?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-&gt;connect_error) { die("Connection failed: " . $conn-&gt;connect_error);
} // Check if an image file was uploaded
if (isset($_FILES["image"]) &amp;&amp; $_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-&gt;prepare($sql); $statement-&gt;bind_param('s', $imgContent); $current_id = $statement-&gt;execute() or die("&lt;b&gt;Error:&lt;/b&gt; Problem on Image Insert&lt;br/&gt;" . 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-&gt;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">&lt;?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-&gt;connect_error) { die("Connection failed: " . $conn-&gt;connect_error); } $result = $conn-&gt;query("SELECT image FROM images ORDER BY id DESC LIMIT 1"); if ($result &amp;&amp; $result-&gt;num_rows &gt; 0) { $row = $result-&gt;fetch_assoc(); $imageData = $row['image']; echo '&lt;img src="data:image/jpeg;base64,' . base64_encode($imageData) . '" alt="Uploaded Image" style="max-width: 500px;"&gt;'; } else { echo 'No image uploaded yet.'; } $conn-&gt;close(); ?&gt;
</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/28/php-upload-image-to-database-with-mysql/