Home  >  Article  >  Backend Development  >  Upload images to database using PHP_PHP tutorial

Upload images to database using PHP_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:03:43944browse

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"];

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/630928.htmlTechArticleToday 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 - the code to put the image into the database imag...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn