Today we will teach you how to upload images to the MYSQL database using PHP. In this tutorial, we need to create three php files:
Readdir. php-code for storing images in the database
Image. php-code for displaying the actual image
View. php-show how you call the image code 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 ");
?>
'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 a difficult part. You need to take a good look at this: classify images and read some of the data in use.
Fopen
'Conversion
Base64_encode
'Insert to 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 it:
<?
Closedir ($ dir_handle );
Echo ("complete ");
Mysql_close ($ dbcnx );
?>
Code for reading images: IMAGE. PHP
This code is difficult. Let's take a look.
<?
$ Dbcnx = mysql_connect ("localhost", "username", "password ");
Mysql_select_db ("base64imgdb ");
?>
The image. php code used for reading images? Img = x:
<?
$ Img = $ _ REQUEST ["img"];
?>
Then we need to connect to the database and read
<?
$ Result = mysql_query ("SELECT * FROM images WHERE imgid =". $ img ."");
If (! $ Result ){
Echo ("<B> Request error:". mysql_error (). "</B> ");
Exit ();
}
While ($ row = mysql_fetch_array ($ result )){
$ Imgid = $ row ["imgid"];