Home > Article > Backend Development > Upload images to database using PHP_PHP tutorial
Today I will teach you how to use PHP to upload images to a MYSQL database. In this tutorial we need to create 3 PHP files:
readdir.php - code for putting images into the database
image.php - code that displays the actual image
view.php - code that shows how you call images in the database
1. Create a database
CREATE TABLE `images` (
`imgid` INT NOT NULL AUTO_INCREMENT ,
`sixfourdata` LONGTEXT NOT NULL ,
PRIMARY KEY ( `imgid` )
);
READDIR.PHP
Specific content:
$dbcnx = mysql_connect("localhost", "username", "password");
mysql_select_db("base64imgdb");
?>
'We need to open a directory
"./"
The 'readdir.php file is located in this directory:
$path = "./";
$dir_handle = opendir($path) or die("Unable to open directory $path");
The following is the more difficult part, everyone needs to study it carefully: classify the images and read out some of the data being used
fopen
'Convert
base64_encode
'Insert into table
while ($file = readdir($dir_handle)) {
$filetyp = substr($file, -3);
if ($filetyp == 'gif' OR $filetyp == 'jpg') {
$handle = fopen($path . "/" . $file,'r');
$file_content = fread($handle,filesize($path . "/" . $file));
fclose($handle);
$encoded = chunk_split(base64_encode($file_content));
$sql = "INSERT INTO images SET sixfourdata='$encoded'";
mysql_query($sql);
}
}
?>
Close the set directory and process:
closedir($dir_handle);
echo("complete");
mysql_close($dbcnx);
?>
Code to read the image: IMAGE.PHP
This code is difficult, we need to take a closer look
$dbcnx = mysql_connect("localhost", "username", "password");
mysql_select_db("base64imgdb");
?>
The code we use to read the image image.php?img=x:
$img = $_REQUEST["img"];
?>
After that we need to connect to the database and read out
$result = mysql_query("SELECT * FROM images WHERE imgid=" . $img . "");
if (!$result) {
echo("Request error: " . mysql_error() . "");
exit();
}
while ($row = mysql_fetch_array($result)) {
$imgid = $row["imgid"];