Storing and Retrieving Images in MySQL Database Using PHP
How can you preserve and access images within a MySQL database using PHP? For beginners, understanding this can be daunting. Here's a comprehensive guide to get you started:
Step 1: MySQL Database Preparation
Create a MySQL table for storing images, similar to this example:
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 '' );
Step 2: Storing Image in Database
To write an image to the database:
$imgData = file_get_contents($filename); $size = getimagesize($filename); mysql_connect("localhost", "$username", "$password"); mysql_select_db ("$dbname"); $sql = sprintf("INSERT INTO testblob (image_type, image, image_size, image_name) VALUES ('%s', '%s', '%d', '%s')", mysql_real_escape_string($size['mime']), mysql_real_escape_string($imgData), $size[3], mysql_real_escape_string($_FILES['userfile']['name']) ); mysql_query($sql);
Step 3: Retrieving Image from Database
To display an image from the database:
$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 in a MySQL Database Using PHP?. For more information, please follow other related articles on the PHP Chinese website!