After I managed it to insert blobs into my db I'm trying to Display a BLOB from MySQL.
This is the getImage.php:
<?php
$id = $_GET['id'];
// do some validation here to ensure id is safe
$link = mysql_connect("localhost", "root", "root");
mysql_select_db("user_auth_tutorial");
$sql = "SELECT image FROM testblob WHERE image_id='$id''";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['image'];
?>
Here the HTML:
<img src="getImage.php?id=1" width="200" height="200" />
This is the content of my db:
Unfortunately Dev-Tools throw an internal server 500 Error.
Browser-Output:
Can anybody tell me what I do wrong?
Thank you so much!
try this
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['image']).'"/>';
Related
I am trying to store images into a path and then upload them into my database. The DB is called "store" and the table I'm using is called "images" containing 3 fields: id, name (varchar), image (longblob). The form is the following:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Upload an Image</title>
</head>
<body>
<form action="upload_file.php" method="POST" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="262144000" />
<p>File:</p>
<input type="file" name="image" accept="image/jpeg" accept="image/jpg" accept="image/png" accept="image/gif">
<input type="submit" value="Upload" name="submit" />
</form>
</body>
</html>
The upload_file.php is:
<?php
//Connect to database
$conn=mysql_connect("localhost","root","my_password");
if(!$conn){
die("Could not connect to MySQL");
}
if(!mysql_select_db("store")){
die("Could not open database:".mysql_error());
}
//file properties
$file = $_FILES['image']['tmp_name'];
if(!isset($file)){
echo "<p>Please select an image.</p>";
} else {
//$image = mysql_real_escape_string(file_get_contents($_FILES['image']['tmp_name']));
$image = base64_encode(file_get_contents($_FILES['image']['tmp_name']));
$image_name = mysql_real_escape_string($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE){
echo "<p>Sorry, this is not an image.</p>";
} else {
echo "<p>File is an image. Processing...</p>";
if(!$insert = mysql_query("INSERT INTO images VALUES('','$image_name','$image')")){
echo "<p>Problem uploading image:".mysql_error()."</p>";
} else {
$lastid = mysql_insert_id();
echo "<p>Success!</p>";
echo "<img src=get.php?id=$lastid>";
}
}
}
error_reporting(-1);
?>
And get.php is:
<?php
//Connect to database
$conn=mysql_connect("localhost","root","my_password");
if(!$conn){
die("Could not connect to MySQL");
}
if(!mysql_select_db("store")){
die("Could not open database:".mysql_error());
}
$id = $_REQUEST['id'];
$image = mysql_query("SELECT * FROM images WHERE id=$id");
$image = mysql_fetch_array($image);
$image = $image['image'];
header('Content-type: image/jpg');
echo base64_decode($image);
?>
The images are uploaded, but are not shown. Instead, I get a broken image icon, and I don't understand why. Can someone help me??
Try to solve this problem step by step
This process can be identified as three parts and split up quickly. The HTML form, the PHP upload and saving to database process, and the loading from database process.
Try echoing the image data before inserting it into the database to see if the data is actually correct.
Update the database and see if the data is inserted there.
Load the image data from the database and echo it to see if it loads it correctly.
Try the full script.
This is just an example checklist. But you can change this and add more steps to it.
Also, please consider updating to MySQLi. You are using deprecated functions which could lead to security issues. Many information sources regarding this subject can be found on the web.
Correct the get.php code with this code
<?php
//Connect to database
$conn = mysql_connect("localhost", "tester", "");
if (!$conn) {
die("Could not connect to MySQL");
}
if (!mysql_select_db("tester")) {
die("Could not open database:" . mysql_error());
}
$id = $_REQUEST['id'];
$rows = mysql_query("SELECT * FROM images WHERE id=$id");
$image = mysql_fetch_assoc($rows);
$image = $image['image'];
header('Content-type: image/jpg');
echo base64_decode($image);
You have to change the database name and user whit your own
These are the parts that i have changed:
$rows = mysql_query("SELECT * FROM images WHERE id=$id");
$image = mysql_fetch_assoc($rows);
echo base64_decode($image);
image is not displaying from the database it show just showing broken image
<?php
$con = mysql_connect('localhost', 'root', ''); //Update hostname
mysql_select_db("postad", $con); //Update database name
$query = "SELECT path1 FROM img_tbl";
$result = mysql_query($query) or die('Error : ' . mysql_error());
$row = mysql_fetch_array($result);
$photo = $row['path1'];
echo "<center><img src=$photo alt=Profile Photo>";
?>
$photo is path right
then try this
echo '<center><img src='.$photo.'alt="Profile Photo"></center>';
Moving from the comments, this is the fix you need:
echo '<center><img src= '.$photo.' alt="Profile Photo"></center>';
Change second last line with this
echo '<center><img src="'.$photo.'" alt="Profile Photo"></center>';
This will work if $photo path is correct...
I want to load image, but the solution that I can get so far is loading a separate script with db - reconnection.
I have a init.php file which basically start up the application with db connection.
looks something like this.
if(!isset($_SESSION)){
session_start();
}
//error_reporting(0); //dont show path name errors when error occurs
// include required files
require 'databases/connect.php';
I have this line of code which tells the blob script to retrieve image Data
<img src="../core/functions/images.php?image_id=<?php echo $responses[$i]['product_id']; ?>" height="150" width="180" alt=""/>
And this is the problem script that re-connect db again and then retrieve the image data. If I do not reconnect the db, the mysql script will fail. Any help on this, so I don't need to reconnect db?
$connect_error = "Sry, we are working on an error, try later";
mysql_connect('localhost','root','') or die($connect_error);
mysql_select_db('SJ3') or die($connect_error);
if(isset($_GET['image_id'])) {
$sql = "SELECT imageType,imageData FROM output_images WHERE imageId=" . $_GET['image_id'];
$result = mysql_query("$sql") or die("<b>Error:</b> Problem on Retrieving Image BLOB<br/>" . mysql_error());
$row = mysql_fetch_array($result);
header("Content-type: " . $row["imageType"]);
echo $row["imageData"];
}
?>
I am trying to display the last 5 images uploaded to my "store" table in MySql.
I'm a complete noob to PHP and databases and i've been reading a lot on how to do this but no luck.
I can store and display pictures one at a time but i'd like to be able to have a gallery of sorts to show the last 5 uploaded.
any advice or help would be greatly appreciated thanks!
p.s. I know it frowned upon to store pictures to a database like this but this project is just for practice.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Project One</title>
</head>
<body>
<form action="index.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="image"> <input type="submit" value="Upload">
<form>
<p />
<?php
//connect to database
(connect to server)
(select correct DB)
//file properties
$file = $_FILES['image']['tmp_name'];
if (!isset($file))
echo "please select an image.";
else
{
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = $_FILES['image']['name'];
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size==FALSE)
echo "That's not an image.";
else
{
if (!$insert = mysql_query("INSERT INTO store VALUES ('', '$image_name', '$image')"))
echo "Problem Uploading Image.";
else
{
$lastid = mysql_insert_id();
echo "Image uploaded. <p />Your image:<p /><img src=get.php?id=$lastid>";
}
}
}
?>
<p />
<p />
Go to Gallery
</body>
</html>
get.php
<?php
//connect to database
(connect to server)
(select correct DB)
$id = addslashes($_REQUEST['id']);
$image = mysql_query("SELECT * FROM store WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];
header("Content-type: image/jpeg");
echo $image;
?>
This is what I used when I wanted to do something like that... a long time ago! =P
$sql = "SELECT image FROM table WHERE cond ORDER BY xxxx DESC LIMIT 5";
$result = mysqli_query($db,$sql);
while($arraySomething = mysqli_fetch_array($result))
{
echo "<img src='php/imgView.php?imgId=".$arraySomething."' />";
}
I try the first approach with header('content-type: image/jpeg'); but end up with image not shown. After a few google through website I found the solution which I can display image from database to my page
try this:
mysql_connect("localhost","root","")or die("Cannot connect to database"); //keep your db name
mysql_select_db("example_db") or die("Cannot select database");
$sql = "SELECT * FROM `article` where `id` = 56"; // manipulate id ok
$sth = mysql_query($sql);
$result=mysql_fetch_array($sth);
// this is code to display
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image_file'] ).'"/>'
mysql_connect("localhost","root","")or die("Cannot connect to database");
//keep your db name
mysql_select_db("example_db") or die("Cannot select database");
$sql = "SELECT * FROM `article` where `id` = 56";
// manipulate id ok
$sth = mysql_query($sql);
$result=mysql_fetch_array($sth);
// this is code to display
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image_file'] ).'"/> width="xxxx" height="xxxx"';
Add the height and width also
You can also use this function
//Retrieve image from database and display it on html webpage
function displayImageFromDatabase(){
//use global keyword to declare conn inside a function
global $conn;
$sqlselectimageFromDb = "SELECT * FROM `imageuploadphpmysqlblob` ";
$dataFromDb = mysqli_query($conn, $sqlselectimageFromDb);
while ($row = mysqli_fetch_assoc($dataFromDb)) {
echo '<img height="250px" width="250px" src=data:image;base64,'.$row['image'].'/>';
}
Insert it into mysql database like this :
$image = $_FILES['imagefile']['tmp_name'];
$name = $_FILES['imagefile']['name'];
$image = base64_encode(file_get_contents(addslashes($image)));
references : https://mauricemutetingundi.blogspot.com/2019/04/how-to-upload-blob-image-to-mysql.html
Instead of storing images using BLOB in mySQL, I have decided to attempt to use a referencing path instead. So I stored images into my "localhost" folder:
localhost/dvd_artwork/image.jpg
Therefore in my database, under column "dvdimage_path" I have TEXT "dvd_artwork/image.jpg" where my id = 1
However, I can't seem to get this to work at the moment
my catalog.php:
<img src="getImage.php?id=1" alt="" width="175" height="200" />
my getimage.php:
<?php
$id = $_GET['id'];
// do some validation here to ensure id is safe
$link = mysql_connect("localhost", "root", "");
mysql_select_db("dvddb");
$sql = "SELECT dvdimage_path FROM dvd WHERE id=$id";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
echo $row['dvdimage_path'];
?>
is there anything wrong?
remove quotes from mysql_query
// Change that
$result = mysql_query("$sql");
// To that
$result = mysql_query($sql);
This doesn't make any sense – getImage returns a string, not an image...
You probably want to replace the getImage href, and just generate the page like this:
<?php
$id = $_GET['id'];
// do some validation here to ensure id is safe
$link = mysql_connect("localhost", "root", "");
mysql_select_db("dvddb");
$sql = "SELECT dvdimage_path FROM dvd WHERE id=$id";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
mysql_close($link);
?>
<img src="<?= $row['dvdimage_path'] ?>" alt="" width="175" height="200" />
...or you want to use file_get_contents on the path, then echo that out with the appropriate headers:
<?php
$id = $_GET['id'];
// do some validation here to ensure id is safe
$link = mysql_connect("localhost", "root", "");
mysql_select_db("dvddb");
$sql = "SELECT dvdimage_path FROM dvd WHERE id=$id";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
mysql_close($link);
header('Content-Type: image/jpeg'); // Or png, or whatever...
echo file_get_contents($_SERVER['DOCUMENT_ROOT'].$row['dvdimage_path']); // might need a slash between the two variables here...
?>
I'd recommend the first way if possible, as it then has the benefits of allowing normal header usage via your server config.