UPDATE.
I can only display the images inside a query e.g.
if($Result = mysqli_query($Link, $Query)){
while($row = mysqli_fetch_array($Result))
{
$img = $row['path'];
echo '<img src="'.$img.'">';
}
}
I want to display them inside a table but this code doesn't work :
<td class="tcgimagecell" colspan="5"><?php echo '<img src="'.$img.'">'; ?></td>
BELOW ISSUE RESOLVED :
I have images stored in a folder (uploads) and the path is stored in a database table in a field named path. I am trying to display the stored images.
$Link = mysqli_connect($Host, $User, $Password, $Database);
$Query = "SELECT * FROM $images";
if($Result = mysqli_query($Link, $Query)){
while($row = mysqli_fetch_array($Result))
{
$img = "uploads/" . $_FILES["file"]["name"];
echo '<img src="'.$img.'">';
}
}
Your folder permissions for "uploads/" might not be set to public read. Have you checked those already? What is the URL that is output for your image? Have you tried Copying URL and linked directly to it from your browser? If the URL is coming back blank, try $row instead of $_FILES since you are just wanting the path to the file.
This line is wrong: $img = "uploads/" . $_FILES["file"]["name"];.
Replace it with $img = "uploads/" . $row[x]; where x is the number of column where file name is
OR
with $img = "uploads/" . $row['columnname'];. Here you have to replace columnname.
Related
I am using phpmyadmin for creating my database. I have stored images in a folder called - "images". The path of the image is stored in the database.
I now want to fetch an image corresponding to an id and display it on the screen.
This is how I am storing my image.
function GetImageExtension($imagetype)
{
if(empty($imagetype)) return false;
switch($imagetype) {
case 'image/bmp': return '.bmp';
case 'image/gif': return '.gif';
case 'image/jpeg': return '.jpg';
case 'image/png': return '.png';
default: return false;
}
}
if (!empty($_FILES["uploaded_image"]["name"]))
{
$file_name=$_FILES["uploaded_image"]["name"];
$temp_name=$_FILES["uploaded_image"]["tmp_name"];
$imgtype=$_FILES["uploaded_image"]["type"];
$ext= GetImageExtension($imgtype);
$imagename=date("d-m-Y")."-".time().$ext;
$target_path = "images/".$imagename;
if(move_uploaded_file($temp_name, $target_path)) {
$query="insert into users(images_path,submission_date,image_name)values('".$target_path."','".date("Y-m-d")."','$imagename')";
Now, I want to fetch the image and display it on the screen.This is the code I have written -
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("project", $connection);
$query = mysql_query("select * from users where _id= '$r'");
$rows = mysql_num_rows($query);
if ($rows == 1 ) {
$row1=mysql_fetch_assoc($query);
$image=$row1["images_path"];
}
What should I write after this so that the image is displayed?
Use the image in an image tag like you normally would with an image URL.
echo '<img src="/'.$image.'" alt="an image"/>';
You may need to adjust the image path to be relative to the site root by prepending /path/to/images/ if your "images" folder is not in the site root.
If you get the correct path after your query, you can use the HTML tag with the parameter src= and the variable holding the path to your image. You need to know the name of the image of course
Simply build up an Image using the $image as the SRC attribute and then echo it back like so:
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("project", $connection);
$query = mysql_query("select * from users where _id= '$r'");
$rows = mysql_num_rows($query);
$imgHTML = ""; // INITIALIZE THE IMAGE HTML TO NOTHING SO THAT YOU CAN STILL ECHO THIS VARIABLE IF THERE IS NO IMAGE
if ($rows == 1 ) {
$row1 = mysql_fetch_assoc($query);
$image = $row1["images_path"];
// JUST BUILD AN HTML REPRESENTATION OF YOUR IMAGE LIKE YOU WOULD IN NORMAL HTML BUT WITH PHP
$imgHTML = "<img alt='ALTERNATIVE_IMAGE_NAME' class='img_class' id='img_id' src='" . $image . "' />";
}
// NOW SIMPLY DISPLAY THE IMAGE.....
echo $imgHTML;
echo '<img src="'.$image.'" />';
OR
echo '<img src="'.$yourWebsiteBaseURL.'/'.$image.'" />';
I'm making an upload application and I have a script that once the images are uploaded they are resized but the original dimensions are stored to be used later on. the index.php should should show the images on the screen.
I've stored the image path instead of a blob on the database and using the 'path' variable to show it on the browser.
The search works but the images are not displaying and I can't find the reason why.
Im new to php/mysql so any help is appreciated on why my images are not showing up.
upload.php
<?php
require_once 'includes/config.inc.php';
require_once 'includes/functions.php';
// Add the heading to output
$output = '<h1>Gallery</h1>';
// Echo the gathered output
echo $output;
// Include the HTML header
include_once 'includes/head.html';
// Check if the form has been submitted...
if (isset($_POST['fileupload'])
&& isset($_POST['title']) && isset($_POST['description'])) {
$title = $_POST['title'];
$description = $_POST['description'];
if (is_uploaded_file($_FILES['userfile']['tmp_name'] )) {
$updir = dirname(__FILE__).'/uploads/';
//$upfilename = $_FILES['userfile']['name'];
$ext=end(explode(".", $_FILES['userfile']['name']));//gets extension
$newname = $updir.$title;
$tmpname = $_FILES['userfile']['tmp_name'];
$newimage = $newname.'.'.$ext;
$path = $newimage;
//if file is an image, upload it
if($_FILES['userfile']['type'] == 'image/jpeg'){
if (move_uploaded_file($tmpname, $newimage)) {
//print if file was uploaded
//echo 'File successfully uploaded';
list($width, $height) = getimagesize($newimage);
//Add values to the DB
$sql = "INSERT INTO Images VALUES(NULL, '$title', '$description', '$width', '$height', '$path')";
$result = mysqli_query($link, $sql);
if(!$result) die ("Database access failed: " . $link->error);
$w = $width;
$h = $height;
resize($newimage, $width, $height);
}
} else {
//print if file failed
echo 'File upload failed';
}
}
//echo debug();
}
// Include the HTML footer
?>
index.php(The sql script is here)
<?php
require_once 'includes/config.inc.php';
require_once 'includes/functions.php';
if (!isset($_GET['page'])) {
$id = 'home'; // display home page
} else {
$id = $_GET['page']; // else requested page
}
switch ($id) {
case 'home' :
include 'uploads.php';
break;
default :
include 'views/404.php';
}
$sql = 'SELECT * FROM Images';
$result = mysqli_query($link, $sql);
if(!$result){
die(mysqli_error($link));
}else{
while($row = mysqli_fetch_array($result)){
echo '<div><a href= "#">
<img src="'.$row['path'].'" width=150 height=150 alt="'.$row['title'].'" /></a></div>';
}
mysqli_free_result($result);
}
/*
Alternative way of showing the right images
$images = glob('uploads/*.jpg');
for($i = 0; $i < count($images); $i++){
list($w,$h) = getimagesize($images[$i]);
$allimages = $images[$i];
echo '<div><a href="'.$allimages.'">
<img src="'.$allimages.'" width="'.$w.'" height="'.$h.'" alt="" /></a>
</div><br/>';
}*/
include_once 'includes/footer.html';
?>
The problem is that you are using dirname(__FILE__) for the start of the path of your image and store that complete path in the database.
According to the manual dirname:
Returns the path of the parent directory.
And __FILE__:
The full path and filename of the file with symlinks resolved.
So you are storing your image using a absolute path on the local file system of the server.
However, that absolute path is not absolute relative to the root of the web-server so the browser will not find the images.
The solution is to use an absolute path when you move the uploaded image, but store a path that is absolute relative to the root of the web-server.
In your case you can probably use the /uploads/ path for that although that would depend on the exact file structure:
...
// no dirname here
$updir = '/uploads/';
//$upfilename = $_FILES['userfile']['name'];
$ext=end(explode(".", $_FILES['userfile']['name']));//gets extension
$newname = $updir.$title;
$tmpname = $_FILES['userfile']['tmp_name'];
$newimage = $newname.'.'.$ext;
$path = $newimage;
//if file is an image, upload it
if($_FILES['userfile']['type'] == 'image/jpeg'){
// only use dirname() here
if (move_uploaded_file($tmpname, dirname(__FILE__) . $newimage)) {
...
You have to add domain of your server to the src attribute of img tag so it'll became an absolute path for users to see the images:
echo '<div><a href= "#">
<img src="'$_SERVER['HTTP_HOST'].$row['path'].'" width=150 height=150 alt="'.$row['title'].'" /></a></div>';
here i am trying to upload the employee profile picture to mysql and then i want to fetch those picture. now i can uploaded the image into mysql db successfully but, when i try to fetch the image that doesn't fetch properly. if you open an image in texteditor na how it will look like? the same thing i got it now.. like this... (QÕf0±Ó%"÷YúEûVÚo¾e9°R}È"!5®?•Ÿ\¯ž›ÃÕîYU0T³¼´œ\aVë%z€ÙBðŒÆnPÈ Qx•eú0´ÁPÁ”·=ó-)Oyá+×½ÄS„ÞšÅS!Y¨;,¾¤ª5HÅÓôÍó3Áº¶j/"5±•RX›ee.&{ +C˜ H CÌai,F+Ô#”?Ì8««IÐO%IW).
my question is how to fetch the image properly? and then is there any other way to do store an image to mysql db. for example save a employee profile pictures to one folder and then store that link to mysql???
index.php code:
<form enctype="multipart/form-data" action="img.php" method="post" name="changer">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
<?php
include("config.php");
$query = mysql_query("SELECT * FROM tbl_images");
while($row = mysql_fetch_array($query))
{
echo "" . $row['image'] . "";
}
?>
img.php code:
<?
include("config.php");
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO tbl_images ";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link) or die(mysql_error());
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
?>
Can you try this,
echo '<img src="data:image/png;base64,' . base64_encode($row['image']) . '" />';
Your code:
while($row = mysql_fetch_array($query))
{
echo '<img src="data:image/png;base64,' . base64_encode($row['image']) . '" />';
}
please check the column size where you are saving the file content. The probable reason to me that you are not able to retrieve the images could be that the data is being trimmed due to size limit of the column. Try increasing the size of the column and changing the data type also, if needed. You may try the longblob datatype.
Encapsulate the echo statement in <img> tags
<form enctype="multipart/form-data" action="img.php" method="post" name="changer">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
<?php
include("config.php");
$query = mysql_query("SELECT * FROM tbl_images");
while($row = mysql_fetch_array($query))
{
echo "<img src=". $row['image'] . "/>"; // Do like this
}
?>
You need to have it rendered in the HTML as an img tag.
You should consider storing the image in a directory on the server and storing the image name/location in the database. Then create an img tag from that.
you must store you image in a folder and rename the file unique name along with the extension.
and store filename in mysql database table. i think the given code will help you.
<?
include("config.php");
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$tmpName = $_FILES['image']['tmp_name'];
$filename = $_FILES['image']['name'];
$ext = getExtension($filename);
$new_file = "uniquename_of_file.".$ext; // you can generate unique name by any way you want.
move_uploaded_file($_FILES['image']['tmp_name'],$DESTINATION_FOLDER."/".$new_file; // upload file to the destination folder with new name
$query = "INSERT INTO tbl_images ";
$query .= "(image) VALUES ('$new_file')";
$results = mysql_query($query, $link) or die(mysql_error()); // insert new name into the database
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
?>
function of getting extension will be as follows
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
Found several examples online on how to upload an image to a mysql database table, in binary
NOT a link or a folder in the server.
the imag isn't viewable when i try to print it
when I check the database table,it shows a bunch of data in weird format, i'm assuming the image data
here is code
if(!empty($_FILES['image']) && $_FILES['image']['size'] > 0 && !empty($_POST['name']))
{
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
code for displaying image
$sql = "SELECT * FROM `photos` WHERE userName = '$currentUser'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$content = $row['image'];
echo $content;
echo '<p id="caption">'.$row['caption'].' </p>';
}
when i try to display the image i get nothing as output, i check the database via putty, and i see a massive amount of weird characters, i'm assuming the items for the image.
ideas?
you could eventually try to replace these two lines:
$content = $row['image'];
echo $content;
with:
echo '<img src="data:image/jpeg;base64,' . base64_encode( $row['image'] ) . '" />';
I have used MySQL to save a image as a blob type. I 'm uploading files through PHP and when I get the image back I revive only a part of it. How can I improve the max size ? (my image file size is less than 300 KB)
PHP uploader...
if($_FILES!=null && $_POST!=null){
$file = $_FILES["image"]["tmp_name"];
if(!isset($file)){
echo "Please upload an image";
}else{
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$type=$_POST['type'];
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size==FALSE)
echo "That's not an image.";
else
{
if(!(mysql_query("INSERT INTO store (name,image,type) values ('$image_name','$image','$type')")))
echo "Problem uploading image";
else
{
$lastid = mysql_insert_id();
echo "Image uploaded. <p /> Your image: <p /> <img id='imageId' src=get.php?id=$lastid>";
}
}
}
}
retrieving image
$id = addslashes($_REQUEST['id']) ;
$imageRow = mysql_query("SELECT * FROM store WHERE id=$id");
$image = mysql_fetch_assoc($imageRow);
$image = $image['image'];
header("Content-type: image/jpg");
echo $image;
You can use different types of blobs. Blob, Mediumblob, longblob, etc.
http://dev.mysql.com/doc/refman/5.0/en/blob.html
Use mysql_real_escape_string() to escape the image data, instead of addslashes(). addslashes() isn't meant for binary.
Use image like this:
<img src='file_display.php?id=<?php echo $row['id']; ?>' width='100' height='100'>
Here, $row['id'] is record primary key - id
and in file_display.php:
// some basic sanity checks
if(isset($_GET['id']) && is_numeric($_GET['id'])) {
//connect to the db
$link = mysql_connect($host, $username, $password) or die("Could not connect: " . mysql_error());
// select our database
mysql_select_db($database) or die(mysql_error());
// get the image from the db
$sql = "SELECT image FROM tbl_images 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);
}
It works for me with WAMP 2.x package
you can use this following code ::
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$id = $_GET['id'];
$sql = mysql_query(" SELECT * FROM store WHERE id=$id") or die(mysql_error());
$row = mysql_fetch_array($sql);
header('Content: image/jpeg');
echo $row['image'];
?>