I would like to know how to display an image stored in a database inside of a particular div using PHP code?
The code I used looks like that:
<form method="post">
<input type="button" name="show" value="show"/><br/>
<input type="image" id="image_show" name="img" value="img"/>
</post>
if(#$_POST['show'])
{
$sql="select imageData form images ORDER BY DESC";
$result=mysql_query($sql) or die('invalid query'.mysql_error());
//set header
header("Content-type:image/png");
echo mysql_result($result,0);
while( $row = mysql_fetch_row( $result ) )
{
echo "<img src='".$row[0]."'/>";
}
}
But it does not work. How can I solve this task?
You need to specify the name of the column you want to retrieve from your returned array (imageData in this case)
echo '<img src="'.$row['imageData'].'"/>";
Also, if dont need this line if you just want to show the image and now force the download:
//set header
header("Content-type:image/png");
It will throw you an error anyway as you are printing information before it with that form.
echo "<img src='".$row['imageData']."'/>";
If the data is embedded in the database as blob, use:
<img src="data:image/png;base64,ABC"/>
With 'ABC' is the image in base64.
Please see here for more information on data URL.
Related
Today i am looking for help. This is my first time asking so sorry in advance if I make a few mistakes
I am trying to code a small web application that will display images.Originally I used the blob format to store my images in a database, however from researching on here People suggest to use a file system. My issue is I cannot display an image. It could be a very small error or even a bad reference to a files location however I cannot make it work.
This is a small project that I hope to be able to improve on and hopefully create into a sort of photo gallery. I am running this application on a localhost.
I am having an issue with displaying images from a filesystem.
// index.php
<form action="process.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="submit" value="Upload" />
</form>
My form then leads to a process page where the request is dealt with.
<?php
// process.php
// connect to the database
include 'connection.php';
// take in some file data
$filename =$_FILES['image']['name'];
// get the file extension
$extension = strtolower(substr($filename, strpos($filename, '.')+1));
// if the file name is set
if(isset($filename)){
// set save destination
$saved ='images/';
// rename file
$filename = time().rand().".".$extension;
$tmp_name=$_FILES['image']['tmp_name'];
// move image to the desired folder
if(move_uploaded_file($tmp_name, $saved.$filename)){
echo "Success!";
// if success insert location into database
$insert="INSERT INTO stored (folder_name,file_name) VALUES('$saved', '$filename')";
// if the query is correct
if($result=mysqli_query($con,$insert)){
echo "DONE";
echo"</br>";
// attempt to print image
echo "<img src=getimage.php?file_name=$filename>";
}
}
}
else{
echo "Please select a photo!!";
}
?>
Now as you can see I have an < img > tag. To try and learn, I was trying to just display the recently uploaded image. To try and do this I created a getimage file.
<?php
//getimage.php
// set the page to display images
header("Content-Type: image/jpeg");
include "connection.php";
// get requested filename
$name = ($_GET['file_name']);
$query = "SELECT * FROM stored WHERE file_name=$name";
$image = mysqli_query($con,$query);
$row = mysqli_fetch_array($image,MYSQLI_ASSOC);
$img = $row['file_name'];
echo $img;
?>
My database structure is as follows:
database name = db_file.
table name = stored.
columns = folder_name, file_name
Again, this is just a small project so I know I will have to alter the database if I wish to create a larger more efficient application.
It seems you use the database lookup to get just the file name, but you already have the file name. Try adding the folder name, create a valid path.
change
$img = $row['file_name'];
to
$img = $row['folder_name'] . '/' . $row['file_name'];
check your <img>tag to see if the correct url is present. You may or may not need the '/', it depends on how you stored the folder name. You may need to add the domain name. There is just not enough information know what is needed.
Your <img> should look like this
<img href="http://www.yourdomain.com/folder name/file name">
in the end
I have found a lot of posts that describe the same problem, but everything I tried failed.
For a profile page I am making people can upload 4 pictures. When no picture is available I want to show a default picture. My complete code is like this now:
$id = $_GET['ID'];
$link = mysql_connect("xxx", "xxx", "xxx");
mysql_select_db("xxx");
$sql = "SELECT * FROM profielen WHERE ID = $id";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
if ($row['Foto4'] == NULL){
//echo '<img src="/img/noImage.jpg" />';
echo $row['Foto5'];
}
else {
echo $row['Foto4'];
}
In this form the code works, so I know that the if-statement is correct.
When I try to uncomment the commented line, it shows a broken link as the image.
I have tried with double quotes and then escape the double quotes within the img tag. I have also tried to call it as a variable and without a / before the img-path. And also just tried to say echo "No image", but it seems that if I do anything else than echo $row[x] it just does not work. When I try to display the image in HTML it works fine, so the name of the file is correct.
I am running out of ideas, so maybe someone can help?
The problem with your code is that you're sending HTML to embed an image back, when really, you should be sending image data back. You can solve this by redirecting the user to the "noImage.jpg", in this way the user will get an image back from the request and all will be fine :)
Code for this could look like this:
if ($row['Foto4'] == NULL){
header('Location: /image/noImage.jpg');
} else {
echo $row['Foto4'];
}
If you use the content type image/jpeg, the browser expects the raw binary data of an image. Instead, you give it HTML-code.
You can instead use the Location-header, which tells the browser to open another address.
header("Location: /img/noImage.jpg");
Remember that you cannot output any other data or write any other headers if you use this method.
EDIT : I might just make it a more 'step-by-step' process i.e.
Seeing as it feels more user-friendly & it's only for <5 images. I have read & appreciate all of the help that I have received so far.
I'm fairly new to PHP & I'm building a basic PHP image editor which may allow multiple image data auditing which is then inserted into a MySQL database. A limit of 5 images may be uploaded at a time for this system (implying that there will only be a low amount of records to play with), but I'll get to that further down.
GUI:
Some of the data columns used:
image id
caption
description
published
imageposition
delete button
All images are echo'd in a while loop by a previous 'SELECT *' result set. Each image will have the 'image id' echo'd inside each input name, so output will be for example:
caption-2, description-2, published-2, imageposition-2, caption-3, description-3
Also, the data values from the previous resultset are echo'd into the input value, allowing the client to edit the current data that exists in the database. There is only one submit button.
My question:
I want to be able to post all of the modified image(s) data to a processor.php form which will then allow me to insert it as an INSERT sql string into the MySQL images table. I need the PHP to be dynamic incase:
images are deleted (image id)
new images are uploaded (image id)
If there is an easier way of doing any of the above, I am welcome to new ideas/opinions. Sorry in advance for my poor understanding of PHP.
Once you get result from 'select *' statement you do foreach
foreach ($images as $image) {
?>
<img src="imagesrc">
<input type="text" name="title_<?php echo $image['image_id'] ; ?>" value="<?php echo $image['title']; ?>">
<input type="text" name="desc_<?php echo $image['image_id'] ; ?>" value="<?php echo $image['description']; ?>">
<input type="button" onclick="markDeleted('<?php echo $image['image_id'] ; ?>')">
<?php } ?>
.....
Once you receive the post value you can explode with "_" and you will get the Primary key and you can update the image table with image ID.
In the javascript function markDeleted you can set the primary key in some hidden field and sent to process.php.
Add it like comma separated 1,2,3 like this (Split by comma in action page)
function markDeleted (imageId)
{
document.getElementById('deleted_image_ids').value = imageId + ","
}
To delete the records easily :
<form action="processor.php" method="post">
<?php
foreach ($images as $img) { // assuming $images is the result set of your sql query
?>
<input type="text" name="name<?php $img['image_id'];?>" value="<?php $img['caption'];?>">
<input type="text" name="desc<?php $img['image_id'];?>" value="<?php $img['description'];?>">
...
<a href="http://yoursiteurl/deleteimg.php?id=<?php $img['image_id']?>">
<?php } ?>
</form>
In deleteimg.php :
<?php
$del = $_POST[id];
$query = $msqli->prepare("DELETE FROM imagetablename WHERE image_id=?");
$query->bind_param( 's', $del );
$query->;execute();
?>
Updating and adding new rows may involve javascript, and much more harder.
How do I Limit some information displayed from the database and add a link eg "More" to enable read all information in a drop down using PHP. such as what is on facebook (Read more...). I am dealing with a lot of content and I dont want it all displayed at once.
Here is part of the code
echo "<p>".$row['Firstname']." ".$row['Lastname']."</p>";
echo "<p>".$row["Course"]." | ".$row["RegID"]."</p>";
echo "<p>".$row["Email"]."</p>";
echo "<p>"."Tel:".$row["Telephone"]."</p>";
echo "<p>".$row["info"]."</p>";
The code is running well only that I want to limit the information
echo "<p>".$row["info"]."</p>";
so that not all is displayed
Thanks
Use Jquery-ui click on "view source" and you'll see it's very simple really, just set the row that you want as the header (what's clicked to show the rest) and store the rest in a div below.
Split info into two strings, one intro, and the rest. Display only the intro to begin with. Insert a link that displays the rest when clicked.
$intro = substr($row['info'], 0, 200);
$rest = substr($row['info'], 200);
echo sprintf(
<<<HTML
<p>
<span class="intro">%s</span><span class="rest" class="display: none">%s</span>
Show more
</p>
HTML
, htmlentities($intro)
, htmlentities($rest)
);
displayRest is a Javascript-function that, given a link, finds the previous span with class rest, shows it and removes the link. I leave it as an exercise to implement this in a way that fits your project. You can go with native Javascript, or use a library such as jQuery, YUI, MooTools, Prototype etc.
if(isset($_POST['more']))
{
$query="select col1,col2,col3, ... ,colN from tableName ";
}
else
{
$query="select col1,col2,col3 from tableName ";
}
//HTML
<form method="post">
<input type="submit" name="more" value="More" />
</form>
//PHP
$records=mysql_query($query);
while($row=mysql_fetch_assoc($records))
{
//Display
}
The limit must be fixed on the SQL request.
// If you want to transmit limitation with a GET PARAMETER.
// You can also $_POST ur data.
$limitation = $_GET['limit'];
//..... And in your SQL REQUEST
$sql = "SELECT * FROM your_table LIMIT 0 , $limitation";
//And in the link....
echo 'Show only 10 Results'
?>
You can optimize that and add security precaution to prevent errors when $limitation receive empty or non numeric parameters.
<?php if(isset($_GET['limit']) && !empty($_GET['limit']) && !preg_match(EXPRESSION, $_GET['limit'])){
//YOU CAN DO THE LIMITATION WHITOUT SQL ERRORS
}
else{
//ERROR DIRECTIVE
}
?>
I've trimmed my code down to the bare minimum to try to find why I cannot display any image that I upload & store via PHP into MySQL. If anyone can point out my error(s) I'd be most grateful.
On execution, the browser reports that the image cannot be displayed as it contains errors.
However, the image uploads & displays fine in other databases running in this same environment.
I've checked that the database holds a blob after upload.
I guess I'm missing something obvious.
Upload form..
<body>
<form enctype="multipart/form-data" action="imagetestprocess.php" method="post">
<input type="file" name="image">
<input type="submit" value="Submit">
</form>
Form handler..
<?php
include("../mylibrary/login.php");
login();
$imagefile = file_get_contents($_FILES['image']['tmp_name']);
$imagefile = mysql_real_escape_string($imagefile);
$query="UPDATE pieces SET image_full='$imagefile' WHERE assetno='1'";
$result = mysql_query($query);
?>
Image displayer..
<?php
include("../mylibrary/login.php");
login();
echo "<body>";
echo "before";
echo "<img src=\"showimage.php\" alt=\"showimage\">";
echo "after";
?>
called function...
<?php
include("../mylibrary/login.php");
login();
$query = "select * from pieces where assetno='1'";
$result=mysql_query($query);
$row=mysql_fetch_array($result, MYSQL_ASSOC);
$image=$row['image_full'];
header("Content-type: image/jpeg");
echo $image;
?>
change the image_full field type to MEDIUMBLOB / BLOB
user this $image = chunk_split(base64_encode(file_get_contents("image.jpg")));
instead of $imagefile = file_get_contents($_FILES['image']['tmp_name']);
and in show image function use image as below.
header("Content-type: image/jpeg");
echo base64_decode($image);
use mysql_escape_string or addslashes and clear your browser cache to see if it works
If the above solutions does not work for you.
Try increasing the length of the field in database.
if still it does not work,
You can check if the image format is RGB or CMYK.
format shoud be RGB to see on screen.
To make it sure you can try opening the same image file in browser.
I think it has something to do with your database encoding. some encoding does not support binary data.
If you cannot change the encoding, maybe you css base64 encode the data before saving and decode it when displaying. only thing is base64 will increase the size by 3.