Storing and Retrieving Images in MySQL Using PHP
Question:
How can I insert and retrieve images from a MySQL database using PHP?
Answer:
To store and retrieve images in MySQL using PHP, follow these steps:
Creating the MySQL Table:
Create a table in your database to store images. For 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 '' );
Inserting Images:
To insert an image into 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);
Retrieving Images:
To display an image from the database in a web page:
$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 to Insert and Retrieve Images from a MySQL Database Using PHP?. For more information, please follow other related articles on the PHP Chinese website!