Mysql database has data type blob where we can store image data. Create a
table which will keep mime type and image content. Table structure
should be like below:
create table img(id int primary key auto_increment,
image blob,
ext varchar(255));
Create a PHP script with form having property method “post” and enctype “multipart/form-data”. Add file container tag in the form with submit button. See below example:
<form method=”post” enctype=”multipart/form-data”><input type=”file” name=”photo”>
<input type=”submit” name=”submit” value=”submit”>
</form>
PHP CODE IS:
/*
Save Images in the database
Please create below table inorder to execute this code;
********** IMG TABLE ********************
create table img(
id int primary key auto_increment,
image blob,
ext varchar(255));
********** IMG TABLE ********************
*/
$db = mysql_connect("localhost", "root", "");
mysql_select_db("test", $db);
if (isset($_POST['submit'])) {
if (isset($_FILES['photo']))
{
$imginfo = getimagesize($_FILES['photo']['tmp_name']);
$mime = $imginfo['mime'];
$data = file_get_contents($_FILES['photo']['tmp_name']);
$data = mysql_real_escape_string($data);
// Preparing data to be used in MySQL query
mysql_query("INSERT INTO img
set ext='$mime', image = '$data'") or die(mysql_error());
}
}
$sql = "select * from img";
$res = mysql_query($sql);
if ($res) {
while($row = mysql_fetch_assoc($res)) {
$image = $row['image'];
echo '<img src= "data:'.$row['ext'].';base64,'.base64_encode($image).'" />';
}
}
create table img(id int primary key auto_increment,
image blob,
ext varchar(255));
Create a PHP script with form having property method “post” and enctype “multipart/form-data”. Add file container tag in the form with submit button. See below example:
<form method=”post” enctype=”multipart/form-data”><input type=”file” name=”photo”>
<input type=”submit” name=”submit” value=”submit”>
</form>
PHP CODE IS:
/*
Save Images in the database
Please create below table inorder to execute this code;
********** IMG TABLE ********************
create table img(
id int primary key auto_increment,
image blob,
ext varchar(255));
********** IMG TABLE ********************
*/
$db = mysql_connect("localhost", "root", "");
mysql_select_db("test", $db);
if (isset($_POST['submit'])) {
if (isset($_FILES['photo']))
{
$imginfo = getimagesize($_FILES['photo']['tmp_name']);
$mime = $imginfo['mime'];
$data = file_get_contents($_FILES['photo']['tmp_name']);
$data = mysql_real_escape_string($data);
// Preparing data to be used in MySQL query
mysql_query("INSERT INTO img
set ext='$mime', image = '$data'") or die(mysql_error());
}
}
$sql = "select * from img";
$res = mysql_query($sql);
if ($res) {
while($row = mysql_fetch_assoc($res)) {
$image = $row['image'];
echo '<img src= "data:'.$row['ext'].';base64,'.base64_encode($image).'" />';
}
}
No comments:
Post a Comment