Storing and Retrieving Images Using MySQL and PHP
Inserting an image into a MySQL database involves creating a table to store the images and then executing an SQL query to insert the image data. To start, a MySQL table called "testblob" is created with columns for storing the image, its type, size, category, and name.
create table testblob ( image_id tinyint(3) not null default '0', image_type varchar(25) not null default '', image blob not null, image_size varchar(25) not null default '', image_ctgy varchar(25) not null default '', image_name varchar(50) not null default '' );
Inserting an image into this table is achieved using an SQL query that specifies the image type, actual image data, image size, and image name.
$imgData = file_get_contents($filename); $size = getimagesize($filename); mysql_connect("localhost", "$username", "$password"); mysql_select_db ("$dbname"); // mysqli // $link = mysqli_connect("localhost", $username, $password,$dbname); $sql = sprintf("INSERT INTO testblob (image_type, image, image_size, image_name) VALUES ('%s', '%s', '%d', '%s')", /*** * For all mysqli_ functions below, the syntax is: * mysqli_whartever($link, $functionContents); ***/ mysql_real_escape_string($size['mime']), mysql_real_escape_string($imgData), $size[3], mysql_real_escape_string($_FILES['userfile']['name']) ); mysql_query($sql);
Retrieving an image from the database can be done using another SQL query that selects the image data from the appropriate table.
$link = mysql_connect("localhost", "username", "password"); mysql_select_db("testblob"); $sql = "SELECT image FROM testblob WHERE image_id=0"; $result = mysql_query("$sql"); header("Content-type: image/jpeg"); echo mysql_result($result, 0); mysql_close($link);
The above is the detailed content of How Can I Store and Retrieve Images Using MySQL and PHP?. For more information, please follow other related articles on the PHP Chinese website!