Inserting the Image into MySQL
Create a new file named insert.php. If you change the name of this file you will also need to change the action="" part in your HTML file above. Open the file in your favorite text editor or PHP IDE.
Write or copy/paste this code into your file:
$username = "YourUserName";
$password = "YourPassword";
$host = "localhost";
$database = "binary";
$link = mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db ($database);
The above code sets your connection variables, creates a connection to MySQL and selects your database (binary if you followed my instructions above). Next we need to read the form data and insert it into the database.
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO tbl_images ";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link);
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
mysql_close($link);
?>
The PHP code above takes the user selected image, reads it with fopen and stores the data in a variable named $data. The binary data is then inserted into our database for retrieval at a later time.
Save the file above and access add.html via your browser. Select an image file and upload it.