Unable to show Images stored in mySQL using PHP - php

I am trying to store images in mySQL database and then displaying on the other page. I have this function to store images in mySQL.
function upload() {
include "databaseConnection.php";
$maxsize = 10000000; //set to approx 10 MB
//check associated error code
if ($_FILES['userfile']['error'] == UPLOAD_ERR_OK) {
//check whether file is uploaded with HTTP POST
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
//checks size of uploaded image on server side
if ($_FILES['userfile']['size'] < $maxsize) {
// prepare the image for insertion
$imgData = addslashes(file_get_contents($_FILES['userfile']['tmp_name']));
// put the image in the db...
// database connection
mysql_connect($host, $user, $pass) OR DIE(mysql_error());
// select the db
mysql_select_db($db) OR DIE("Unable to select db" . mysql_error());
// our sql query
$sql = "INSERT INTO carsinfo
(carName, carPicture)
VALUES
('{$_FILES['userfile']['name']}', '{$imgData}');";
// insert the image
mysql_query($sql) or die("Error in Query: " . mysql_error());
$msg = '<p>Image successfully saved in database with id =' . mysql_insert_id() . ' </p>';
} else {
// if the file is not less than the maximum allowed, print an error
$msg = '<div>File exceeds the Maximum File limit</div>
<div>Maximum File limit is ' . $maxsize . ' bytes</div>
<div>File ' . $_FILES['userfile']['name'] . ' is ' . $_FILES['userfile']['size'] .
' bytes</div><hr />';
}
}
else
$msg = "File not uploaded successfully.";
}
else {
$msg = file_upload_error_message($_FILES['userfile']['error']);
}
return $msg;
}
And this code to show iamges.
<?php
include "databaseConnection.php";
// just so we know it is broken
error_reporting(E_ALL);
// some basic sanity checks
//connect to the db
$link = mysql_connect("$host", "$user", "$pass") or die("Could not connect: " . mysql_error());
// select our database
mysql_select_db("$db") or die(mysql_error());
// get the image from the db
$sql = "SELECT carPicture FROM carsinfo;";
// the result of the query
$result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
$row = mysql_fetch_assoc($result);
// set the header for the image
echo $row['carPicture'];
header("Content-type: image/jpeg");
// close the db link
mysql_close($link);
?>
When this code is run, nothing is shown on the page, even if I write some HTML inside this code, empty page is shown.

I assume you are saving the image content as blob and if your sql is returning the correct data then you can display as
header("Content-type: image/jpeg");
echo $row['carPicture'];
You need to add the header first before the image.
or
echo '<img src="data:image/jpeg;base64,' . base64_encode($row['carPicture']) . '">';

do not write
include databaseConnection.php
nothing include anything.

Related

How to display an image stored in Mysql database with special date not by id (php)

I am trying to display an image uploaded to my "upload" table in MySql. I've been reading a lot on how to do this but no luck.
"news_content" table is for uploading NEWS content to Mysql and has 6 columns: id,title, description, content_text, date, time
and "upload" table has 5 columns: id, name, size, image, date
In "news_content" table I upload the date and the time columns separately but the date column in "upload" table is a string concatenated with both date and time. For example if in "news_content" table the date is 2/3/2016 and the time is 5:30, in "upload" table the date is going to be 2/3/20165:30. I organized it that way in order to retrieve the image by its specific date and time that the related post uploaded.
I upload the image in news.php page with this following code:
news.php :
// Create connection
$connection = mysql_connect("localhost","root","p206405az");
// Check connection
if (!$connection) {
die("Connection failed: " . mysql_error());
}
//select a database to use
$db_select = mysql_select_db( "news" , $connection) ;
if (!$db_select) { die("Selection faild:" . mysql_error()) ;
}
//uploading the content of news and date and time
if(isset($_POST["submit"])){
$title = $_POST["title"] ;
$description = $_POST["description"] ;
$content_text = $_POST["content_text"] ;
$date = $_POST["date"] ;
$time = $_POST["time"] ;
//perform mysql query
$result = mysql_query("INSERT INTO news_content (title, description, content_text, date, time)
VALUES ('$title', '$description', '$content_text' ,'$date' , '$time' )") ;
if (!$result) {
die("Insert failed: " . mysql_error());
$submitMessage = "Problem with updating the post, please try again" ;
} else if ($result){
$submitMessage = "Your post succsessfully updated" ;
}
}
// uploading the image
if(isset($_POST['submit']) && $_FILES['image']['size'] > 0)
{
$fileName = $_FILES['image']['name'];
$tmpName = $_FILES['image']['tmp_name'];
$fileSize = $_FILES['image']['size'];
$fileType = $_FILES['image']['type'];
$filedate = "$date" . "$time" ;
$fp = fopen($tmpName, 'r');
$content2 = fread($fp, filesize($tmpName));
$content3 = addslashes($content2);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO upload (name, size, type, image, date ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content3', '$filedate')";
mysql_query($query) or die('Error2, query failed');
}
And I want to retrieve that image by getImage.php page to use it as source page later by this following code but it seems it can't retrieve the blob data:
P.S. The image is successfully uploaded but I can't retrieve it with specific date that I Posted lately
getImage.php :
// Create connection
$connection = mysql_connect("localhost","root","p206405az");
// Check connection
if (!$connection) {
die("Connection failed: " . mysql_error());
}
//select a database to use
$db_select = mysql_select_db( "news" , $connection) ;
if (!$db_select) { die("Selection faild:" . mysql_error()) ;
}
//perform mysql query
$result = mysql_query("SELECT * FROM news_content" , $connection);
if (!$result) {
die("read failed: " . mysql_error());
}
//useing returned data
while ($content = mysql_fetch_array($result)){
$date = $content["date"];
$time = $content["time"] ;
}
$filedate = "$date" . "$time" ;
$result2 = mysql_query("SELECT image FROM upload WHERE date='$filedate'" , $connection);
if (!$result2) {
die("read failed: " . mysql_error());
};
$row = mysql_fetch_assoc($result2);
mysql_close($connection);
header("Content-type: image/jpeg");
echo $row['image'];
And I want to display the image in index.php page with this following HTML code:
index.php :
<img src="getImage.php?date=<?php echo $filedate ; ?>" width="175" height="200" />
How can I retrieve that data in getImage.php page and then use that page az source page to display the image in index.php page?
Any help would be appreciated.
cant figure out the error unless php throws an error. but i would save the images as files instead of db and keep its name if news table's row, unless there are multiple images per news.
in case of multimple image per news, i would just match the image id to news id.
schema for news.db
id, title, description, content_text, date, time
schema for upload.db:
id, image, newsid
my image html link would have been:
<img src="getImage.php?id=<?php echo $newsid; ?>" width="175" height="200" />
and then my getimage.php would have been like this:
$connection = mysql_connect("localhost","root","p206405az");
if (!$connection) {
die("Connection failed: " . mysql_error());
}
$db_select = mysql_select_db( "images" , $connection) ;
if (!$db_select) {
die("Selection faild:" . mysql_error()) ;
}
$id=$_GET["id"];
$result = mysql_query("SELECT image FROM upload WHERE newsid='$id' LIMIT 1" , $connection);
if (!$result) {
die("read failed: " . mysql_error());
};
$row = mysql_fetch_assoc($result);
mysql_close($connection);
header("Content-type: image/jpeg");
print $row['image'];
To show errors:
add error_reporting(E_ALL); ini_set('display_errors', '1'); at top of your page;
temporarily comment the header line: header("Content-type: image/jpeg");;
retrieve image directly from browser address bar (see image below);
If you obtain a “500 Server Error” check your Apache error log (compile errors are not displayed even with error_reporting enabled);

I ensure database that has image and the database connect is correct ,but I cannot display the image

My display code is :
<?php
include "file_constants.php";
// just so we know it is broken
error_reporting(E_ALL);
// some basic sanity checks
if(isset($_GET['id']) && is_numeric($_GET['id'])) {
//connect to the db
$link = mysql_connect("$host", "$user", "$pass")
or die("Could not connect: " . mysql_error());
// select our database
mysql_select_db("$db") or die(mysql_error());
// get the image from the db
$sql = "SELECT image FROM test_image WHERE id=" .$_GET['id'] . ";";
// the result of the query
$result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
// set the header for the image
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
// close the db link
mysql_close($link);
}
else {
echo 'Please use a real id number';
}
?>
I ensure database that has image and the database connect is correct.
I can upload image from php to phpmyadmin (MYSQL).
However, I cannot display the image.(http:// /file_display.php?id=1)
Can someone help me to display image in php?? THANK YOU SO MUCH!
The file-insert code:
<html>
<head><title>File Insert</title></head>
<body>
<h3>Please Choose a File and click Submit</h3>
<form enctype="multipart/form-data" action=
"<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<input name="userfile" type="file" />
<input type="submit" value="Submit" />
</form>
<?php
// check if a file was submitted
if(!isset($_FILES['userfile']))
{
echo '<p>Please select a file</p>';
}
else
{
try {
$msg= upload(); //this will upload your image
echo $msg; //Message showing success or failure.
}
catch(Exception $e) {
echo $e->getMessage();
echo 'Sorry, could not upload file';
}
}
// the upload function
function upload() {
include "file_constants.php";
$maxsize = 10000000; //set to approx 10 MB
//check associated error code
if($_FILES['userfile']['error']==UPLOAD_ERR_OK) {
//check whether file is uploaded with HTTP POST
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
//checks size of uploaded image on server side
if( $_FILES['userfile']['size'] < $maxsize) {
//checks whether uploaded file is of image type
//if(strpos(mime_content_type($_FILES['userfile']['tmp_name']),"image")===0) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
if(strpos(finfo_file($finfo, $_FILES['userfile']['tmp_name']),"image")===0) {
// prepare the image for insertion
$imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name']));
// put the image in the db...
// database connection
mysql_connect($host, $user, $pass) OR DIE (mysql_error());
// select the db
mysql_select_db ($db) OR DIE ("Unable to select db".mysql_error());
// our sql query
$sql = "INSERT INTO test_image
(image, name)
VALUES
('{$imgData}', '{$_FILES['userfile']['name']}');";
// insert the image
mysql_query($sql) or die("Error in Query: " . mysql_error());
$msg='<p>Image successfully saved in database with id ='. mysql_insert_id().' </p>';
}
else
$msg="<p>Uploaded file is not an image.</p>";
}
else {
// if the file is not less than the maximum allowed, print an error
$msg='<div>File exceeds the Maximum File limit</div>
<div>Maximum File limit is '.$maxsize.' bytes</div>
<div>File '.$_FILES['userfile']['name'].' is '.$_FILES['userfile']['size'].
' bytes</div><hr />';
}
}
else
$msg="File not uploaded successfully.";
}
else {
$msg= file_upload_error_message($_FILES['userfile']['error']);
}
return $msg;
}
// Function to return error message based on error code
function file_upload_error_message($error_code) {
switch ($error_code) {
case UPLOAD_ERR_INI_SIZE:
return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
case UPLOAD_ERR_FORM_SIZE:
return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
case UPLOAD_ERR_PARTIAL:
return 'The uploaded file was only partially uploaded';
case UPLOAD_ERR_NO_FILE:
return 'No file was uploaded';
case UPLOAD_ERR_NO_TMP_DIR:
return 'Missing a temporary folder';
case UPLOAD_ERR_CANT_WRITE:
return 'Failed to write file to disk';
case UPLOAD_ERR_EXTENSION:
return 'File upload stopped by extension';
default:
return 'Unknown upload error';
}
}
?>
</body>
</html>
The SQL is:
create table test_image (
id int(10) not null AUTO_INCREMENT PRIMARY KEY,
name varchar(25) not null default '',
image blob not null
);
The tutorial is http://vikasmahajan.wordpress.com/2010/07/07/inserting-and-displaying-images-in-mysql-using-php/
If you saved just the image name in the database , this will display the image in your HTML
<?php
$result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
while($row = mysqli_fetch_array($result)) {
echo '<img src="www.yourdomain.com/your/directory/"'. $row["image "].'/>';
}
?>
NOTE : Dont need to use the while loop if you having only one row

Failed to replace PDF in database with another PDF using PHP

I am trying to replace one pdf that previously upload in MySQL to another pdf . I created an a href [edit] for user to choose the pdf file and link to editDB.php where query update placed.
This is edit.DB.php
<?php
// Connect to the database
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="is"; // Database name
$tbl_name="publication"; // Table name
if(isset($_POST['submit']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$conn = mysql_connect("$host", "$username", "$password");
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
Connect database, fetch file_id, fetch other data that updated
$conn = mysql_connect("$host", "$username", "$password");
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if (isset($_GET["id"]))
{
$id =$_GET["id"];
}
else
{
echo'failed';
}
mysql_select_db($db_name);
$title=mysql_real_escape_string($_POST['title']);
$author=mysql_real_escape_string($_POST['author']);
$year=mysql_real_escape_string($_POST['year']);
$abs=mysql_real_escape_string($_POST['abstract']);
query here
$query="update publication set title='".$title."', author='".$author."', year='".$year."' , abstract='".$abs."', file_name='".$fileName."', file_size='".$fileSize."', file_type='".$fileType."', content='".$content."' where file_id='$id'";
mysql_query($query) or die(mysql_error());
echo '<script type="text/javascript">alert("'.$title.' updated!");
window.location.href="publication.php";
</script>';
mysql_close($conn);
}
?>
The problem I faced is that , after I key in updated info in my edit form. The data successfully direct to editDB.php. pop up dialog showing data updated is shown but the data did not updated both database and the page showing info. I will be grateful for any help hands. Thanks.
Instead of
if (isset($_GET["id"]))
{
$id =$_GET["id"];
}
else
{
echo'failed';
}
i change it to
if(isset($_POST['submit'])&& $_FILES['userfile']['size'] > 0)
{
$id =$_POST["id"];
Of course the id must pass properly and make sure id is match with ur database.
This code can works. Hope able to help you all.

PHP: Upload images from folder to MySQL Database

I have searched a lot on about this but I did not find solution.
I have images in a directory in server. And I want to upload those images ( Not Just image Paths) to MySQL database using longblob with PHP.
I know that storing images in the database is not recommended but that is the requirement of my project so I want use this method.
Please suggest me, How can I do that?
Thanks to all.
<?php
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("your databse name");
// Make sure the user actually
// selected and uploaded a file
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
$name=$_POST['name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// into our database.
$query = "INSERT INTO image2 ";
$query .= "(image,name) VALUES ('$data','$name')";
$results = mysql_query($query, $con);
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
// Close our MySQL Link
mysql_close($con);
?>

How can I have a upload auto linked in a mysql table

I have a form that uploads a file with other information to a database and displays it in a chart. Right now the chart only displays the file name and doesen't link it. If the file was called test1.pdf, how would I make it so on the chart it still says chart1.pdf but links it to the directory that the file is on?
if ('POST' === $_SERVER['REQUEST_METHOD'])
{
$con = mysql_connect("localhost","xxxx","xxxxx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("jjlliinn_test", $con);
$target = "clientdoc/";
$target = $target . basename( $_FILES['file']['name']);
$date = $_POST['date'];
$propertydescription = $_POST['propertydescription'];
$transactiontype = $_POST['transactiontype'];
$applicabledocument = ($_FILES['file']['name']);
$received = $_POST['received'];
$paid = $_POST['paid'];
//Writes the to the server
if(move_uploaded_file($_FILES['file']['tmp_name'], $target))
{
//Tells you if its all ok
echo "";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
$sql = mysql_query("INSERT INTO `transactions` (`date`, `agentclient`, `propertydescription`, `transactiontype`, `applicabledocument`, `received`, `paid`)
VALUES
('$date', '$agentclient', '$propertydescription', '$transactiontype', '$applicabledocument', '$received', '$paid')") or die(mysql_error());
$query = mysql_query($sql);
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
echo "Succesfully added transaction. Updating table...";
echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"48\">";
mysql_close($con);
}
}
?>
Assuming all your uploads are stored in the client doc folder and you have run the query to get the recordset from the transactions table...
link text
Another point, looking at the code, sending raw $_POST values direct to the db is asking for sql injection trouble. Have a look at either htmlentities with ENT_QUOTES set or the input filters available with php.

Categories