Create an account

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] PHP Upload Image to Database with MySql

[Tut] PHP Upload Image to Database with MySql

<div style="margin: 5px 5% 10px 5%;"><img src="" width="550" height="320" title="" alt="" /></div><div><div class="modified-on" readability="7.047619047619"> by <a href="">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="">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="">View demo</a></p>
<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 );
<p><img decoding="async" loading="lazy" class="alignnone size-large wp-image-21415" src="" alt="php upload image to database output" width="550" height="320" srcset=" 550w, 300w, 768w, 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>
<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>
<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
<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;
<p><a class="demo" href="">View demo</a> <a class="download" href="">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
<p> <a href="" class="top">↑ Back to Top</a> </p>

Forum Jump:

Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016