Reputation: 159
I want to store image in database directly without storing it in a folder on my explorer. If possible than how? I am using php
with mysql
database to store image and i have define datatype LONGBLOB
to store image in database. Below is my code:
<?php
$conn = mysqli_connect("localhost","root","")or die(mysqli_error($conn));
mysqli_select_db($conn,'image') or die(mysqli_error($conn));
if(isset($_REQUEST['submit'])){
$old = $_FILES['img']['tmp_name'];
$new = $_FILES['img']['name'];
move_uploaded_file($old,$new);
echo $sql = "INSERT INTO img(`img_name`) VALUES('$new')";
$exe = mysqli_query($conn,$sql);
if($exe){
echo "Image Uploaded Successfully....";
}
}
echo $query = "Select `img_name` from `img`";
$ex = mysqli_query($conn,$query);
?>
<html>
<body>
<form method="post" name="myForm" id="myForm" enctype="multipart/form-data">
<div>
<input type="file" name="img"/>
</div>
<div>
<input type="submit" name="submit" value="Upload"/>
</div>
<?php
while($res = mysqli_fetch_array($ex)){
?>
<div>
<img height="50" width="50" src="<?php echo $res['img_name'];?>"/><br/>
</div>
<?php } ?>
</form>
</body>
</html>
Upvotes: 0
Views: 92
Reputation: 1035
You would need to convert the image into base64. something like this:
$path = $_FILES['img']['tmp_name'];
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
It'd be better to save it as a string rather than BLOB if possible. If it has to be a BLOB you'd have to convert the string and then convert it back when you're retrieving from the database. If you store it as a string, the image will even work with the base64 as the src of the image.
Upvotes: 1
Reputation: 1089
move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img");
$instr = fopen("latest.img","rb");
$image = addslashes(fread($instr,filesize("latest.img")));
mysql_query ("insert into pix (mgdata) values ('".image."')");
And after delete uploaded image, image will be in DB
After you can send image from DB to browser
$gotten = @mysql_query("select * from pix order by pid desc limit 1");
if ($row = @mysql_fetch_assoc($gotten)) {
$title = htmlspecialchars($row[title]);
$bytes = $row[imgdata];
}
// If this is the image request, send out the image
if ($_REQUEST[gim] == 1) {
header("Content-type: image/jpeg");
print $bytes;
exit ();
}
?>
Upvotes: 0