How to retrieve and show BLOB Image from database? - php

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);
?>

Related

Search and display the result in the same page

I have small doubt in PHP coding, please help me. Actually I am displaying jobs currently, after searching,the result will displayed in the same page. It is done, but the result is displaying below the content. What I have to do to display only results in that page? I want to make unavailable the previous contents.This is the code:
<html>
<head>
<title>Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h2>Job Openings</h2>
<form method="POST" action="jobopenings.php">
<input type="text" name="txt" required />
<input type="submit" name="btn" value="search" /><br/>
</form>
</body>
</html>
<?php
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('DB', '*****');
$con = mysqli_connect(HOST,USER,PASS,DB) or die("Unable to connect to db");
$selQ = "Select * from jobpostings";
$res1 = mysqli_query($con, $selQ);
while($row = mysqli_fetch_array($res1))
echo $row[3]."<br> Job Id:<b>".$row[2]."</b><br><b>".$row[1]."</b>"."
<br>"."Exp:".$row[5]."<br>"."Location:".$row[6]."<br>".$row[8]."<br><br>";
if(isset($_POST["btn"])){
$query=$_POST['txt'];
$query=htmlspecialchars($query);
$query=mysqli_real_escape_string($con,$query);
$raw_results="select * from jobpostings where (C_name like '%" .$query."%')
or (Job_title like '%".$query."%')";
$final_results=mysqli_query($con,$raw_results);
if(mysqli_num_rows($final_results)>0){
while($results=mysqli_fetch_array($final_results)){
echo "<p><b>".$results[1]."</b><br> Job Id:".$results[2]
<br>".$results[3]."</p>";
}
}
else{
echo '<b style="color:red;">No results found</b>';
}
}
?>
Thanks in advance
Take the whole php code inside <body> and put if conditions to show either of sections. Like this:
<html>
<head>
<title>Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h2>Job Openings</h2>
<?php if(!isset($_POST["btn"]))
{ ?>
<form method="POST" action="jobopenings.php">
<input type="text" name="txt" required />
<input type="submit" name="btn" value="search" /><br/>
</form>
<?php }
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('DB', '*****');
$con = mysqli_connect(HOST,USER,PASS,DB) or die("Unable to connect to db");
$selQ = "Select * from jobpostings";
$res1 = mysqli_query($con, $selQ);
while($row = mysqli_fetch_array($res1))
echo $row[3]."<br> Job Id:<b>".$row[2]."</b><br><b>".$row[1]."</b>"."
<br>"."Exp:".$row[5]."<br>"."Location:".$row[6]."<br>".$row[8]."<br><br>";
if(isset($_POST["btn"])){
$query=$_POST['txt'];
$query=htmlspecialchars($query);
$query=mysqli_real_escape_string($con,$query);
$raw_results="select * from jobpostings where (C_name like '%" .$query."%')
or (Job_title like '%".$query."%')";
$final_results=mysqli_query($con,$raw_results);
if(mysqli_num_rows($final_results)>0){
while($results=mysqli_fetch_array($final_results)){
echo "<p><b>".$results[1]."</b><br> Job Id:".$results[2]
<br>".$results[3]."</p>";
}
}
else{
echo '<b style="color:red;">No results found</b>';
}
}
?>
</body>
</html>
Here is the modified code:
<?php
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('DB', '*****');
$con = mysqli_connect(HOST,USER,PASS,DB) or die("Unable to connect to db");
$final_results = null;
if(isset($_POST["btn"])){
$query=$_POST['txt'];
$query=htmlspecialchars($query);
$query=mysqli_real_escape_string($con,$query);
$raw_results="select * from jobpostings where (C_name like '%" .$query."%') or (Job_title like '%".$query."%')";
$final_results=mysqli_query($con,$raw_results);
}
?>
<html>
<head>
<title>Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h2>Job Openings</h2>
<form method="POST" action="jobopenings.php">
<input type="text" name="txt" required />
<input type="submit" name="btn" value="search" /><br/>
</form>
<?php
if(!is_null($final_results) && mysqli_num_rows($final_results)>0){
while($results=mysqli_fetch_array($final_results)){
echo "<p><b>".$results[1]."</b><br> Job Id:".$results[2]."<br>".$results[3]."</p>";
}
}else{
echo '<b style="color:red;">No results found</b>';
}
$selQ = "Select * from jobpostings";
$res1 = mysqli_query($con, $selQ);
while($row = mysqli_fetch_array($res1))
echo $row[3]."<br> Job Id:<b>".$row[2]."</b><br><b>".$row[1]."</b>"."
<br>"."Exp:".$row[5]."<br>"."Location:".$row[6]."<br>".$row[8]."<br><br>";
?>
</body>
</html>
I didn't test this code, please confirm it works fine.
Also ALWAYS start php code before <html> tag and everything you have to be print must be within <body> tag
1) I would suggest you not to create 2 SQL query (one without search and one with search). You can make one query and append where clause according to the search.
2) "..but the result is displaying below the content." => Wrap all the contents inside <body> tag.
Updated Code
<html>
<head>
<title>Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h2>Job Openings</h2>
<form method="POST" action="jobopenings.php">
<input type="text" name="txt" required />
<input type="submit" name="btn" value="search" /><br/>
</form>
<?php
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('DB', '*****');
$con = mysqli_connect(HOST, USER, PASS, DB) or die("Unable to connect to db");
$where = "";
$searched = false;
if (isset($_POST["btn"]) && isset($_POST['txt'])) {
$searched = true;
$txt = htmlspecialchars($_POST['txt']);
$txt = mysqli_real_escape_string($con, $txt);
$where = "WHERE (C_name like '%" .$txt. "%') or (Job_title like '%" .$txt. "%')";
}
$raw_results = "SELECT * FROM `jobpostings` ".$where;
$final_results = mysqli_query($con, $raw_results);
if (mysqli_num_rows($final_results) > 0) {
while ($results = mysqli_fetch_array($final_results)) {
if(!$searched){
echo "<p><b>".$results[1]."</b><br> Job Id:".$results[2]."<br>".$results[3]."</p>";
} else {
echo $results[3] . "<br> Job Id:<b>" . $results[2] . "</b><br><b>" . $results[1] . "</b>" . "<br>" . "Exp:" . $results[5] . "<br>" . "Location:" . $results[6] . "<br>" . $results[8] . "<br><br>";
}
}
} else {
echo '<b style="color:red;">No results found</b>';
}?>
</body>
</html>
Note: Use Prepared Statements to avoid SQL Injections
<html>
<head>
<title>Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h2>Job Openings</h2>
<form method="POST" action="jobopenings.php">
<input type="text" name="txt" required />
<input type="submit" name="btn" value="search" /><br/>
</form>
<?php
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('DB', '*****');
$con = mysqli_connect(HOST,USER,PASS,DB) or die("Unable to connect to db");
if(isset($_POST["btn"])){
$query=$_POST['txt'];
$query=htmlspecialchars($query);
$query=mysqli_real_escape_string($con,$query);
$raw_results="select * from jobpostings where (C_name like '%" .$query."%')
or (Job_title like '%".$query."%')";
$final_results=mysqli_query($con,$raw_results);
if(mysqli_num_rows($final_results)>0){
while($results=mysqli_fetch_array($final_results)){
echo "<p><b>".$results[1]."</b><br> Job Id:".$results[2]
<br>".$results[3]."</p>";
}
}
else{
echo '<b style="color:red;">No results found</b>';
}
}
else{
$selQ = "Select * from jobpostings";
$res1 = mysqli_query($con, $selQ);
while($row = mysqli_fetch_array($res1))
echo $row[3]."<br> Job Id:<b>".$row[2]."</b><br><b>".$row[1]."</b>"."
<br>"."Exp:".$row[5]."<br>"."Location:".$row[6]."<br>".$row[8]."<br><br>";}
?>
</body>
</html>

PHP not returning mysql results

I am brand new to PHP, or database programming in general. For a project I have to query a bookstore database for book info (a very small database) and display it on the following page. Below is the code for my bookstore search page:
<?php
$con = mysqli_connect("localhost", "root", "root") or die("Error connecting to database: ".mysqli_error());
mysqli_select_db($con, "bookstore") or die(mysqli_error());
?>
<!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=iso-8859-1" />
<title>Book Store</title>
</head>
<body>
<td><h1>Book Search</h1> </td>
<table width="100%" border="0">
<tr>
<form method="post" action="search.php?go" id="searchform">
<input type="text" name="name">
<input type="submit" name="submit" value="Search By Title">
</form>
<form method="post" action="search.php?go" id="searchform">
<input type="text" name="category">
<input type="submit" name="submit" value="Search By Category">
</form>
</tr>
</table>
</body>
</html>
And the following is a simple search.php code that query's my database and returns results. However I am unable to see any results. The only thing that shows up is "Book Title Search Results" with nothing below. Which obviously means my problem is in my while loop.
<?php
$con = mysqli_connect("localhost", "root", "root") or die("Error connecting to database: ".mysqli_error());
mysqli_select_db($con, "bookstore") or die(mysqli_error());
?>
<!DOCTYPE html>
<html>
<head>
<title>Search Results</title>
<meta http-equic="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
if (isset($_POST['name'])){
$query = $_POST['name'];
$sql = mysqli_query($con, "SELECT * FROM books
WHERE (`title` LIKE '%".$query."%')") or die(mysqli_error($con));
if (mysqli_num_rows($sql) > 0) {
echo "</br> Book Title Search Results </br>";
while ($row = mysqli_fetch_array($sql, MYSQL_ASSOC)) {
echo "</br>Title: " .$row['title']. ", Author: " .$row['author'].", Year: " .$row['year'] . ", Price: $" .$row['price'] ."</br>";
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['cover'] ).'"/>';
}
}else{ // if there is no matching rows do following
echo "No results";
}
}
?>
</body>
</html>
I have 6 columns in my database: title, author, year, price, category, image (BLOB FILE), and I have checked naming in my query functions but cannot figure anything out. Can anyone push me in the right direction or show me what I'm doing wrong? I'm using MAMP web server.
There is a typo in your code. Use MYSQLI_ASSOC instead of MYSQL_ASSOC. The rest of the code is correct.
try
$con = mysqli_connect("localhost", "root", "root", "bookstore") or die("Error connecting to database: ".mysqli_error());
In your query, remove the braces after the where:
$sql = mysqli_query($con, "SELECT * FROM books WHERE title LIKE '%$query%'") or die(mysqli_error($con));
Then fetch the results with:
while ($row = mysqli_fetch_assoc($sql)) {
//code
}

Image uploaded in database but not display on page in 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);

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