Image uploaded in database but not display on page in php? - php

I have code for image upload and view in php and MySQL. After click on "Submit" button in "imageUpload.php" page image is stored in database. but not displaying in "listImages.php" page. I don't know what's the problem. I see "image not displaying when uploading in php" but its seems different solution for me. here is my code please have a look where i am wrong.
imageUpload.php :
<?php
/* CREATE TABLE IF NOT EXISTS `output_images`
(
`imageId` tinyint(3) NOT NULL AUTO_INCREMENT,
`imageType` varchar(25) NOT NULL DEFAULT '',
`imageData` mediumblob NOT NULL,
PRIMARY KEY (`imageId`)
) */
if(count($_FILES) > 0) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
mysqli_connect("localhost", "root", "");
mysqli_select_db ("test");
$imgData =addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$sql = "INSERT INTO output_images(imageType ,imageData)
VALUES('{$imageProperties['mime']}', '{$imgData}')";
$current_id = mysqli_query($sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysqli_error());
if(isset($current_id)) {
header("Location: listImages.php");
}
}
}
?>
<HTML>
<HEAD>
<TITLE>Upload Image to MySQL BLOB</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<form name="frmImage" enctype="multipart/form-data" action="" method="post" class="frmImageUpload">
<label>Upload Image File:</label><br/>
<input name="userImage" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" />
</form>
</div>
</BODY>
</HTML>
listImages.php :
<?php
$conn = mysqli_connect("localhost", "root", "");
mysqli_select_db("test");
$sql = "SELECT imageId FROM output_images ORDER BY imageId DESC";
$result = mysqli_query($sql);
?>
<HTML>
<HEAD>
<TITLE>List BLOB Images</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<?php
while($row = mysqli_fetch_array($result)) {
?>
<img src="imageView.php?image_id=<?php echo $row["imageId"]; ?>" /><br/>
<?php
}
mysqli_close($conn);
?>
</BODY>
</HTML>
imageView.php :
<?php
$conn = mysqli_connect("localhost", "root", "");
mysqli_select_db("test") or die(mysqli_error());
if(isset($_GET['image_id'])) {
$sql = "SELECT imageType,imageData FROM output_images WHERE imageId=" . $_GET['image_id'];
$result = mysqli_query("$sql") or die("<b>Error:</b> Problem on Retrieving Image BLOB<br/>" . mysqli_error());
$row = mysqli_fetch_array($result);
header("Content-type: " . $row["imageType"]);
echo $row["imageData"];
}
mysqli_close($conn);
?>

this would help you
<a href="imageView.php?image_id=<?php echo $row["imageId"]; ?>">
<img src="<?php echo $row['imagedata']; ?>" alt="my picture" height="128" width="128" />
</a>

it should be
$conn=mysqli_connect("ur_servername_ex_localhost","ur_username","ur_password","ur_db");
mysqli_query($conn, $sql);

Related

PHP / MYSQL: Upload Image to database with encode base64

Currently, I developed a project that requires user to upload image from Computer. I do this from an example on the internet. For now, the column image at the database uses "BLOB" and the upload successful.
But, I don't want to uses BLOB, I want to change to LONGTEXT. When I change this format, the image saved to the database is successful but the image display is broken. The encode text and column image also looks weird. Can I know what is the problem? Below is the code
<?php
$connect = mysqli_connect("localhost", "root", "", "imagephp");
if(isset($_POST["insert"]))
{
$file = addslashes(file_get_contents($_FILES["image"]["tmp_name"]));
$query = "INSERT INTO tbl_images(name) VALUES ('$file')";
if(mysqli_query($connect, $query))
{
echo '<script>alert("Image Inserted into Database")</script>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:500px;">
<h3 align="center">Insert and Display Images From Mysql Database in PHP</h3>
<br />
<form method="post" enctype="multipart/form-data">
<input type="file" name="image" id="image" />
<br />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info" />
</form>
<br />
<br />
<table class="table table-bordered">
<tr>
<th>Image</th>
</tr>
<?php
$query = "SELECT * FROM tbl_images ORDER BY id DESC";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
echo '
<tr>
<td>
<img src="data:image/jpeg;base64,'.base64_encode($row['name'] ).'" height="200" width="200" class="img-thumnail" />
</td>
</tr>
';
}
?>
</table>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#insert').click(function(){
var image_name = $('#image').val();
if(image_name == '')
{
alert("Please Select Image");
return false;
}
else
{
var extension = $('#image').val().split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
alert('Invalid Image File');
$('#image').val('');
return false;
}
}
});
});
</script>
Hope someone can help me. Thanks!

How to retrieve and show BLOB Image from database?

I am trying to insert and retrieve image from database. All is going well and image is being inserted in database in BLOB format, but when I am trying to retrieve those images it does not appear and only broken icon comes to webpage. The code is given below. Please help.
ImageUpload.php
<?php
if(count($_FILES) > 0) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
mysql_connect("localhost", "root", "");
mysql_select_db ("connection");
$imgData =addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$sql = "INSERT INTO output_images(imageType ,imageData)
VALUES('{$imageProperties['mime']}', '{$imgData}')";
$current_id = mysql_query($sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysql_error());
if(isset($current_id)) {
header("Location: listImages.php");
}
}
}
?>
<HTML>
<HEAD>
<TITLE>Upload Image to MySQL BLOB</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<form name="frmImage" enctype="multipart/form-data" action="" method="post" class="frmImageUpload">
<label>Upload Image File:</label><br/>
<input name="userImage" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" />
</form>
</div>
</BODY>
</HTML>
ListImages.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("connection");
$sql = "SELECT imageId FROM output_images ORDER BY imageId DESC";
$result = mysql_query($sql);
?>
<HTML>
<HEAD>
<TITLE>List BLOB Images</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<?php
while($row = mysql_fetch_array($result)) {
?>
<img src="imageView.php?image_id=<?php echo $row["imageId"]; ?>" /><br/>
<?php
}
mysql_close($conn);
?>
</BODY>
</HTML>
imageView.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("connection") or die(mysql_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"];
}
mysql_close($conn);
?>

Can't display image PHP

My problem is, when I upload a picture to a database, the upload is successful but the picture isn’t displayed. This is my code:
SQL file:
CREATE TABLE `images` (`id` int(11) NOT NULL auto_increment,`name` varchar(100) default NULL,`size` int(11) default NULL,`type` varchar(20) default NULL,`content` mediumblob,PRIMARY KEY (`id`)) ENGINE=MyISAM;
Index.php
<?php if (!empty($uploadOk)): ?>
<div>
<h3>Image Uploaded:</h3>
</div>
<div>
<img src="image.php?id=<?=$imageId ?>" width="150px">
<strong>Embed</strong>: <input size="25" value='<img src="image.php?id=<?=$imageId ?>">'><br>
</div>
<hr>
<? endif; ?>
<form action="index.php" method="post" enctype="multipart/form-data" >
<div>
<h3>Image Upload:</h3>
</div>
<div>
<label>Image</label>
<input type="hidden" name="MAX_FILE_SIZE" value="500000">
<input type="file" name="image" />
<input name="submit" type="submit" value="Upload"><br>
</div>
</form>
</tr>';}mysql_close();?>
image.php
<?php
// verify request id.
if (empty($_GET['id']) || !is_numeric($_GET['id'])) {
echo 'A valid image file id is required to display the image file.';
exit;
}
$imageId = $_GET['id'];
//connect to mysql database
if ($conn = mysqli_connect('localhost', 'username', 'pass', 'db_name')) {
$content = mysqli_real_escape_string($conn, $content);
$sql = "SELECT type, content FROM images where id = {$imageId}";
if ($rs = mysqli_query($conn, $sql)) {
$imageData = mysqli_fetch_array($rs, MYSQLI_ASSOC);
mysqli_free_result($rs);
} else {
echo "Error: Could not get data from mysql database. Please try again.";
}
//close mysqli connection
mysqli_close($conn);
} else {
echo "Error: Could not connect to mysql database. Please try again.";
}
if (!empty($imageData)) {
// show the image.
header("Content-type: {$imageData['type']}");
echo $imageData['content'];
} ?>
getImage.php
<?php
$id = $_GET['id'];
$link = mysql_connect("localhost", "username", "pass");
mysql_select_db("db_name");
$sql = "SELECT content FROM images WHERE id=$id";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['content'];
?>
This code worked. I think the SQL database is incorrect or has problems to display images.
In order to display the image, you should use AJAX from JavaScript.

Retrieve and display images from MySQL database (with condition)

I'm having a problem on developing my website..
First, I have 2 tables:
1- Products: contains info. about the products & 2- Images: which contains product images.
The idea is that : I want to insert an image or two for a specified product and display that image for that product only..
In the mean time, I can insert images into the database and I can also display them.. but my issue is that when I try to do display.. the code retrieves all images from Images table..
so my question: how can I display image/s for only one product .. not all images in that table? I'm confused in how to make this condition.. need ur help guys :?
Here's my code:
File1: imageUpload.php
<?php
if(count($_FILES) > 0) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
mysql_connect("localhost", "root", "");
mysql_select_db ("myDB");
$imgData =addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$sql = "INSERT INTO Images(imageType ,imageData, product_id)
VALUES('{$imageProperties['mime']}', '{$imgData}','{$_POST['memids']}')";
$current_id = mysql_query($sql) or die("<b>Error:</b> Problem on Image Insert<br/>" .
mysql_error());
if(isset($current_id)) {
header("Location: listImages.php");
}
}
}
?>
<HTML>
<HEAD>
<TITLE>Upload Image</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<form name="frmImage" enctype="multipart/form-data" action="" method="post"
class="frmImageUpload">
<label>Upload Image File:</label><br/>
<input name="userImage" type="file" class="inputFile" required/>
<input type="submit" name="submit" value="Submit" class="btnSubmit" /><br><br>
</form>
</div>
</BODY>
</HTML>
File2: listImages.php
<?ob_start()?>
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("myDB");
$sql = "SELECT imageId FROM Images
ORDER BY imageId DESC";
$result = mysql_query($sql);
?>
<HTML>
<HEAD>
<TITLE>List BLOB Images</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<?php
while($row = mysql_fetch_array($result)) {
?>
<img src="imageView.php?image_id=<?php echo $row["imageId"]; ?> "width="200" /><br/>
<?php
}
mysql_close($conn);
?>
</BODY>
</HTML>
<?ob_flush()?>
File3: imageView.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("myDB") or die(mysql_error());
if(isset($_GET['image_id'])) {
$sql = "SELECT imageType,imageData FROM 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"];
}
mysql_close($conn);
?>

(PHP) The Image cannot be displayed because it contains errors

I've read almost all topics related to this. i dont know whats causing it.
This is code for showing images
<html>
<body>
<?php
mysql_connect('localhost','root','') or die("Unable to Connect: ".mysql_error());
mysql_select_db("punjabi") or die("Unable to Select Database: ".mysql_error());
$sql = "SELECT imagename, mimetype, imagedata
FROM images WHERE ID = 1";
$result = #mysql_query($sql);
if(!$result)
{
die(mysql_error());
}
$file = mysql_fetch_array($result);
$imagename = $file['imagename'];
$mimetype = $file['mimetype'];
$imagedata = $file['imagedata'];
header("content-type: $mimetype");
echo($imagedata);
?>
This is the code for inserting images
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Add Post</title>
<style type="text/css">
*
{
margin:0px;
padding:0px;
}
</style>
</head>
<body bgcolor="#333333">
<?php if(isset($_POST['submit'])):
{
if (!is_uploaded_file($_FILES['uploadfile']['tmp_name']))
{
die("$uploadfile is not an uploaded file!");
}
$uploadfile = $_FILES['uploadfile']['tmp_name'];
$uploadname = $_FILES['uploadfile']['name'];
$uploadtype = $_FILES['uploadfile']['type'];
$uploaddesc = $_POST['desc'];
$tempfile = fopen($uploadfile,'rb');
$filedata = fread($tempfile,filesize($uploadfile));
$filedata = addslashes($filedata);
$sql = "INSERT INTO images SET
imagename = '$uploadname',
mimetype = '$uploadtype',
description = '$uploaddesc',
imagedata = '$filedata'";
$ok = #mysql_query($sql);
if (!$ok) die("Database error storing file: " .mysql_error());
$sql = "Select id from images where imagename = '$uploadname'";
$result = #mysql_query($sql);
if(!$result) die(mysql_error());
if(mysql_num_rows($result)!=1) die(mysql_error());
$row = mysql_fetch_array($result);
$imageid = $row['id'];
$title = $_POST['title'];
$content = $_POST['content'];
$sql = "INSERT into posts SET
title = '$title',
content = '$content',
imageid = '$imageid'";
if(!#mysql_query($sql))
{
die(mysql_error());
}
header("Location:http://localhost/punjabi/adminhome.php");
}
?>
<?php else: ?>
<div id="post">
<form action="<?php echo($_SERVER['PHP_SELF']) ?>" method="post" enctype="multipart/form-data" >
Title: <input type="text" name="title" /><br /><br /><br />
Content:<br /> <textarea cols=100 rows="40" wrap="hard" name="content" /></textarea><br /><br />
Image: <input type="file" name="uploadfile" /><br /><br />
Image Desc: <input type="text" name="desc" /><br /><br />
<input type="submit" value="Submit" name="submit" />
</form>
</div>
<?php endif; ?>
</body>
</html>
And This is the Table Structure:
CREATE TABLE filestore (
-> ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
-> FileName VARCHAR(255) NOT NULL,
-> MimeType VARCHAR(50) NOT NULL,
-> Description VARCHAR(255) NOT NULL,
-> FileData MEDIUMBLOB
->);
And Help would be appreciated!
The problem is that the headers have already been sent when you do:
<html>
<body>
<?php
So you cannot set the header for the image anymore:
header("content-type: $mimetype");
Just getting rid of the html (an image is not html / text) before the php tag should solve that.

Categories