Show image in the page after uploading and inserting it to database - php

I want to show the image in my page after uploading and inserting it into the database. The image is used for my image slider. The reason i want to show the image here is to easily manage the image slider. That page is my admin. Im new to php and mysql, can someone give me ideas, what requirements, hints to do it?
here is the picture what i want to do.. like thumbnail
here is my slider its working.
NOTE: the image button is to upload the image.
here is my image slider code.
<?php
include('connect.php');
?>
<!DOCTYPE html>
<html>
<head>
<link href="css/style.css" rel="stylesheet" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="js/slider.js"></script>
<script>
$(document).ready(function () {
$('.flexslider').flexslider({
animation: 'fade',
controlsContainer: '.flexslider'
});
});
</script>
</head>
<body>
<div class="container">
<div class="flexslider">
<ul class="slides">
<?php
// Creating query to fetch images from database.
$query = mysqli_query($mysqli, "SELECT * from images order by id desc limit 5");
$result = $query;
while($r = mysqli_fetch_array($result)){
?>
<li>
<img src="<?php echo $r['photo'];?>" width="400px" height="300px"/>
</li>
<?php
}
?>
</ul>
</div>
</div>
</body>
</html>
here is my admin.php this is where i want to show the image.
<?php
//for connecting db
include('connect.php');
if (!isset($_FILES['image']['tmp_name'])) {
echo "";
}
else
{
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"gallery/" . $_FILES["image"]["name"]);
$photo="gallery/" . $_FILES["image"]["name"];
$query = mysqli_query($mysqli, "INSERT INTO images(photo)VALUES('$photo')");
$result = $query;
echo '<script type="text/javascript">alert("image successfully uploaded ");window.location=\'admin.php\';</script>';
}
?>
<form class="form" action="" method="POST" enctype="multipart/form-data">
<div class="image">
<p>Upload images and try your self </p>
<div class="col-sm-4">
<input class="form-control" id="image" name="image" type="file" onchange='AlertFilesize();'/>
<input type="submit" value="image"/>
</div>
</div>
</form>
here is my connect.php code
<?php
// hostname or ip of server
$servername='localhost';
// username and password to log onto db server
$dbusername='root';
$dbpassword='';
// name of database
$dbname='pegasus';
////////////// Do not edit below/////////
$mysqli = new mysqli($servername,$dbusername,$dbpassword,$dbname);
if($mysqli->connect_errno){
printf("Connect failed: %s\n", $mysql->connect_error);
exit();
}
?>

One approach would be to use glob to see if there are any files in the gallery folder
Something along the lines of:
<?php foreach(glob('./path/to/gallery/folder/*.{jpg,gif,png}', GLOB_BRACE) as $image): ?>
<img src="<?= $image; ?>" />
<?php endforeach; ?>
One benefit of this approach is that if there are no images, nothing will show and you're also saving a db query.
Or to make use of your database query again...
Copy this from your first file..
<?php
// Creating query to fetch images from database.
$query = mysqli_query($mysqli, "SELECT * from images order by id desc limit 5");
$result = $query;
while($r = mysqli_fetch_array($result)){
?>
<img src="<?php echo $r['photo'];?>" width="400px" height="300px"/>
<?php
}
?>
and reuse it in your file that you want to display the images
Reference: glob

Related

how to retrieve multiple images from database in html <img> tag

I want to retrieve these images from database.
<html>
<body>
<?php
$servername="localhost";
$username="root";
$pass="";
$db="db";
$conn=new mysqli($servername,$username,$pass,$db);
$result=$conn->query("select * from image");
while($row_brand=mysqli_fetch_array($result))
{
$brand_image=$row_brand['image'];
?>
<div class="div1">
<?php
echo "<img src='uploads/$brand_image' />";
echo <img src="image.php?id=<? echo $image['id'];?>" />
}
?>
</div>
</body>
</html>
I am using this code to fetch all images.
But I want to fetch images in image <img> tag.
So please help me that how I fetch all these images in html file with the <img> tag.
<html>
<body>
<?php
$servername="localhost";
$username="root";
$pass="";
$db="db";
$conn=new mysqli($servername,$username,$pass,$db);
$result=$conn->query("select * from image");
while($row_brand=mysqli_fetch_array($result))
{
$brand_image[] = $row_brand;
}
?>
<?php foreach($brand_image as $brand){ ?>
<div class="div1">
<img src='uploads/<?php echo $brand["image"]; ?>' />
<img src="image.php?id=<? echo $brand['image_id']; ?>" />
</div>
<?php } ?>
</body>
</html>
Please check this updated code.

How to retrieve image from database and display image on the web page

I have inserted image into database and store name in the table.
my image is saved in a folder named 'Uploads'.
Now need to retrieve image from the databse and display it. when I try to display It only shows the image name which is taken from my table.but it does not show the image.
retrieving code is given below
$sql="SELECT * FROM candi_profile WHERE can_email='{$_SESSION['usr_email']}'";
$result=mysqli_query($con,$sql);
if(!$result) die(mysqli_error($con));
<div class="container">
<!-- Page Header -->
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Employer Dashboard
</h1>
</div>
</div>
<!-- /.row -->
<!-- Projects Row -->
<div class="row">
<div class="col-md-4">
<?php
while($rows=mysqli_fetch_array($result)){
$c_id = $rows['can_id'];
var_dump($c_id);
?>
<p class="lead"><?php echo $rows['can_name'] ?></p>
<div class="profile-sidebar">
<!-- SIDEBAR USERPIC -->
<div class="profile-userpic">
<p class="lead">
<?php echo $rows['pic_name'] ?></p>
</div>
<!-- END SIDEBAR USERPIC -->
<!-- SIDEBAR USER TITLE -->
<div class="profile-usertitle">
<div class="profile-usertitle-name">
Marcus Doe
</div>
<div class="profile-usertitle-job">
<?php echo $rows['can_city'] ?>
<i class="glyphicon glyphicon-map-marker">
</i>
</div>
<div class="profile-usertitle-job">
<i class="glyphicon glyphicon-envelope"></i>
<?php echo $rows['can_email'] ?>
</div>
<div class="profile-usertitle-job">
<?php echo $rows['can_country'] ?>
</div>
</div>
<!-- END SIDEBAR USER TITLE -->
<!-- SIDEBAR BUTTONS -->
<div class="profile-userbuttons">
<hr>
</div>
<!-- END SIDEBAR BUTTONS -->
<!-- SIDEBAR MENU -->
<?php
}
?>
</div>
you can use this code to retrieve image from database
<?php
include 'connection.php'
?>
<?php
$result = mysql_query("SELECT * FROM table") or die(mysql_error());
?>
<table border="1" cellpadding="5" cellspacing="5">
<tr> <th>Image</th></tr>
<?php
while($row = mysql_fetch_array($result)) {
$id = $row['id'];
?>
<tr>
<td><img src="uploads/<?php echo $row['pic_name'];?>" alt=" " height="75" width="75"></td>
</tr>
<?php
}
}
?>
</table>
I assume that the content of $rows['pic_name'] is string only as said on your question.
Put an image attribute and call the path of the image with the corresponding filename save on the database.
<img src = "<path>/<?php echo $rows['pic_name'] ?>" />
NOTE:
Make sure the image is existing on your desire path.
Use image tag to display the image and give it path to the image folder
<img src="your path/<?php echo $rows['pic_name'] ?>" />
friend instead of making images folder you should make a new image column(i.e "imageColumn ") type as blob then
You need to create another php script to return the image data, e.g. getImage.php.
home.php(or display image page) code
<body>
<img src="getImage.php?id=1" width="175" height="200" />
</body>
Then getImage.php is
<?php
$id = $_GET['id'];
// do some validation here to ensure id is safe
$link = mysql_connect("localhost", "root", "");
mysql_select_db("dvddb");
$sql = "SELECT imageColumn FROM Tablename WHERE id=$id";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['imageColumn '];
?>
First fetch image from database using query
The imagejpeg() function is an inbuilt function in PHP which is used to display image to browser or file.
Get data using function ob_get_contents();
Display image in page with height and width
$id = $_GET['id'];
$sql = "select image from table where id='".$id."'";
$res = mysqli_query($sql);
$row = mysqli_fetch_assoc($res);
$image = $row['image'];
ob_start();
imagejpeg($image, null, 50);
$data = ob_get_contents();
ob_end_clean();
echo "<img src='data:image/jpg;base64,'".base64_encode($data)."' style='border:1px
black; border-radius:10px; width:100px; height:125px;'>";

Try to show image but shows a broken link instead

I want to show a picture in my code but for some reason I get a big white almost blank page with a broken link img. I want to show the image and along with any other information.
I also want to resize the image(so it doesnt cover the whole page).
The code:
<?php
session_start()
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0" />
<link rel="stylesheet" href="css/style.css" />
</head>
<div id="Container">
<div id="header">
<h1>Welcome!</h1>
</div>
<div id="navigation">
<?php
include_once "navigation.php";
?>
</div>
<div id="Content">
<?php
if (isset($_GET['search'])) {
$Name = $_GET['search'];
mysql_connect("localhost","root","") or die ("Could not connect to the server!");
mysql_select_db("pictures") or die ("That database could not be found!");
$query = mysql_query("SELECT * FROM picture WHERE Name='$Name'") or die ("The query could not be completed, please try again later!");
if (mysql_num_rows($wepquery) !=1) {
die ("That name could not be found!");
}
while ($row = mysql_fetch_array($query, MYSQL_ASSOC, 0)) {
$dbName = $row['Name'];
$dbCreator = $row['Creator'];
$dbDescription = $row['Description'];
$imageData = $row['Image'];
}
header("Content-type: image/jpeg");
if($Name != $dbName) {
die ("There has been a fatal error. Please try again.");
}
?>
<h2><?php echo $Name; ?></h2>
<br />
<table>
<tr><td>Creator: <?php echo $dbCreator;?></td></tr>
<tr><td>Description:<br /><?php echo $dbDescription;?></td></tr>
<tr><td>Picture:<br /><?php echo $imageData;?></td></tr>
</table>
<?php
} else die ("You need to specify a submission!");
?>
</div>
</div>
</html>
The database:
id, Name, Creator, Description, Image_name, Image(mediumblob).
The last two fields as you can see is dedicated to pictures. Yes I know about PDO and MySQLi, but I just want to finish this code first. Any help?
Images need to either be served by URL or the blob needs to be converted to a data URI like so:
<table>
<tr><td>Creator: <?php echo $dbCreator;?></td></tr>
<tr><td>Description:<br /><?php echo $dbDescription;?></td></tr>
<tr><td>Picture:<br /><?php echo "<img src='data:image/jpeg;base64," . base64_encode( $imageData ) . "' />"; ?></td></tr>
</table>
if you want image you need to enclose it with image tags. assume if your $imageData contains the location of the image then you can do the following.
<img src='<?php echo $imageData;?>' ... />
if your $imageData contains actual binary data of an image you need to create a separate call to a php script to return the imageData. and make the call to be the src attribute of an img tag.
is your path exactly pointing toward the image? have checked "../../" ? another question, is your image really inside an image tag? there must be something like this:
<img src="<?php echo $imagePath; ? />

PHP file in <img> tag cannot be referenced using query string

i m trying to display an image stored in a database by passing the image_id(an auto increment field) into the query string and then including imagedisplay.php(file used to display the image) in image tag. The problem is that this file, imagedisplay.php is not access ie the control never seems to go into the file. The code for both the main file and the imagedisplay.php file are below. Please note that i m not able to write the head part of the code here due to some formatting issue. The head section is standard html section pre-formatted in Dreamweaver.
<body>
<div class="page shadow-round">
<div id="header">
<div id="logo">
<script type="text/javascript" src="../js/header.js"></script>
</div>
</div>
<div id="menu">
<script type="text/javascript" src="../js/navmenu.js"></script>
<script type="text/javascript">
</script>
</div>
<div class="content overflow" style="height:900px;">
<?php
require_once 'login.php'; //contains the classes for connecting to databases
$dbh=new DB_Mysql; //executing queries
$func=new DB_Mysql_code_functions;
session_start();
if(isset($_SESSION['username']))
{
echo<<<_END
<form method="post" action="admin_social_activities.php" enctype="multipart/form-data">
<table width="990">
<tbody>
<tr><td>Select an image file to be uploaded:</td></tr>
<tr><td><input type="submit" value="UPLOAD" /></td></tr>
</tbody>
</table>
</form>
_END;
if(isset($_FILES['imagefile']['tmp_name']))
{
$imagefile=$_FILES['imagefile']['tmp_name'];
$image_size=$_FILES['imagefile']['size'];
$image_name=addslashes($_FILES['imagefile']['name']);
$image_data = addslashes(file_get_contents($imagefile));
$image_array=getimagesize($imagefile);
$image_type=$image_array['mime'];
$image_height=$image_array[1];
$image_width=$image_array[0];
$maxfilesize=2000000;
if($maxfilesize<$image_size)
{
echo "Please upload a smaller image. The size of the image is too large.";
}
else
{
$query="INSERT INTO gallery(image_name,image_type,image,image_size) VALUES ('". $image_name."','".$image_type."','".$image_data."','".$image_size."')";
$stmt=$dbh->execute($query);
$lastimageid=mysql_insert_id();
echo "<p>You uploaded this image</p>";
echo "<img src='imagedisplay.php?imageid=".$lastimageid."' />";
}
}
}
else
echo "<br/><br/> Your are <span class=\"red\"><b>not Authorized</b></span> to view this page. If you are the Admin, please login with your credentials again. <a href='login_page.php'>Click here to continue</a>";
?>
</div>
</body>
</html>
Now the problem is that the control never goes to imagedisplay.php ie. it fails to reference imagedisplay.php altogether.
the code for imagedisplay.php is below:
<?php
require_once 'login.php';
$dbh= new DB_Mysql();
$func=new DB_Mysql_code_functions;
$id=$_GET['imageid'];
$query="SELECT * FROM gallery where image_id=".$id;
$stmt=$dbh->execute($query);
$row=$stmt->fetch_row();
$imagedata=$row[3];
header("Content-type:image/jpeg");
echo $imagedata;
?>
I have tried all permutation combinations with the quotes, tried echo statements to see if control enters the file....but it does not...it stays in the main file only...i dont understand the reason...please help...please don't worry about SQL injections as i plan to deal with them later, once the code starts working....thanks
Your echo command should be like this:
echo '<img src="imagedisplay.php?imageid=' . $lastimageid . ' " />';
Look at your generated HTML source and make sure it's right. Check your error log to see if you are getting any errors from your image script.

Cannot display image stored in MySQL database after connecting to database through php

I am a complete novice and have just begin working with images in PHP and MySQL database. Here is the problem:
The image is being successfully stored in the database table in BLOB field. I can write that in a file(new.jpg) and display the image. Now here is the twsiter - the imagedisplay.php file i created to display the image on the web page can read the new.jpg file from the folder directory. But as soon as i connect to the database to fetch the image data directly from the database (so that i do not have to include new.jpg in the code), it start showing the error "The image contains errors....."
The code used for uploading the image is
<?php
require_once 'login.php'; //contains the classes for connecting to databases
$dbh=new DB_Mysql; //executing queries
$func=new DB_Mysql_code_functions;
session_start();
if(isset($_SESSION['username']))
{
echo<<<_END
<form method="post" action="admin_social_activities.php" enctype="multipart/form-data">
<table width="990">
<tbody>
<tr><td>Select an image file to be uploaded:</td></tr>
<tr><td><input type="submit" value="UPLOAD" /></td></tr>
</tbody>
</table>
</form>
_END;
if(isset($_FILES['imagefile']['tmp_name']))
{
$imagefile=$_FILES['imagefile']['tmp_name'];
$image_size=$_FILES['imagefile']['size'];
$image_name=addslashes($_FILES['imagefile']['name']);
$image_data = addslashes(file_get_contents($imagefile));
$image_array=getimagesize($imagefile);
$image_type=$image_array['mime'];
$image_height=$image_array[1];
$image_width=$image_array[0];
$maxfilesize=2000000;
if($maxfilesize<$image_size)
{
echo "Please upload a smaller image. The size of the image is too large.";
}
else
{
$query="INSERT INTO allery(image_name,image_type,image,image_size) VALUES ('".$image_name."','".$image_type."','".$image_data."','".$image_size."')";
$stmt=$dbh->execute($query);
$lastimageid=mysql_insert_id();
$query="select * from gallery where mage_id=".$lastimageid;
$stmt=$dbh->execute($query);
$row=$stmt->fetch_row();
if(file_exists("new.jpg"))
unlink("new.jpg");
$handle=fopen("new.jpg",'wb');
fwrite($handle,$row[3]);
fclose($handle);
echo "<p>You uploaded this image</p><img src='imagedisplay.php' height=".($image_height/2)." width=".($image_width/2).">";
}
}
}
and the current code for imagedisplay.php file is below and it displays the image fine:
<?php
header("Content-type: image/jpeg");
$image=imagecreatefromjpeg("new.jpg");
imagejpeg($image);
imagedestroy($image);
?>
It stops displaying image as soon as i include the connection query in imagedisplay.php
<?php
require_once 'login.php';
$dbh= new DB_Mysql();
$func=new DB_Mysql_code_functions;
header("Content-type: image/jpeg");
$image=imagecreatefromjpeg("new.jpg");
imagejpeg($image);
imagedestroy($image);
?>
I m stuck on this since days...please help..
OK...so i changed my approach...i m now passing the image_id into the query string and then including imagedisplay.php image tag:
Please note that i m not able to write the head part of the code here due to some formating issue. The head section is standard html section pre formatted in Dreamweaver.
<body>
<div class="page shadow-round">
<div id="header">
<div id="logo">
<script type="text/javascript" src="../js/header.js"></script>
</div>
</div>
<div id="menu">
<script type="text/javascript" src="../js/navmenu.js"></script>
<script type="text/javascript">
</script>
</div>
<div class="content overflow" style="height:900px;">
<?php
require_once 'login.php'; //contains the classes for connecting to databases
$dbh=new DB_Mysql; //executing queries
$func=new DB_Mysql_code_functions;
session_start();
if(isset($_SESSION['username']))
{
echo<<<_END
<form method="post" action="admin_social_activities.php" enctype="multipart/form-data">
<table width="990">
<tbody>
<tr><td>Select an image file to be uploaded:</td></tr>
<tr><td><input type="submit" value="UPLOAD" /></td></tr>
</tbody>
</table>
</form>
_END;
if(isset($_FILES['imagefile']['tmp_name']))
{
$imagefile=$_FILES['imagefile']['tmp_name'];
$image_size=$_FILES['imagefile']['size'];
$image_name=addslashes($_FILES['imagefile']['name']);
$image_data = addslashes(file_get_contents($imagefile));
$image_array=getimagesize($imagefile);
$image_type=$image_array['mime'];
$image_height=$image_array[1];
$image_width=$image_array[0];
$maxfilesize=2000000;
if($maxfilesize<$image_size)
{
echo "Please upload a smaller image. The size of the image is too large.";
}
else
{
$query="INSERT INTO gallery(image_name,image_type,image,image_size) VALUES ('".$image_name."','".$image_type."','".$image_data."','".$image_size."')";
$stmt=$dbh->execute($query);
$lastimageid=mysql_insert_id();
echo "<p>You uploaded this image</p>";
echo "<img src='imagedisplay.php?imageid=".$lastimageid."' />";
}
}
}
else
echo "<br/><br/> Your are <span class=\"red\"><b>not Authorized</b></span> to view this page. If you are the Admin, please login with your credentials again. <a href='login_page.php'>Click here to continue</a>";
?>
</div>
</body>
</html>
Now the problem is that the control never goes to imagedisplay.php ie. it fails to reference imagedisplay.php altogether.
the code for imagedisplay.php is below:
<?php
require_once 'login.php';
$dbh= new DB_Mysql();
$func=new DB_Mysql_code_functions;
$id=$_GET['imageid'];
$query="SELECT * FROM gallery where image_id=".$id;
$stmt=$dbh->execute($query);
$row=$stmt->fetch_row();
$imagedata=$row[3];
header("Content-type:image/jpeg");
echo $imagedata;
?>
I have tried all permutation combinations with the quotes, tried echo statements to see if control enters the file....but it does not...it stays in the main file only...i dont understand the reason...please help...
You have some errors in your queries ("allery", "mage_id").
$query="INSERT INTO allery(image_name,image_type,image,image_size) VALUES ('".$image_name."','".$image_type."','".$image_data."','".$image_size."')";
...
$query="select * from gallery where mage_id=".$lastimageid;
If you have errors anywhere in your code in imagedisplay.php, they will be output and end up in the image data, corrupting it. See what imagedisplay.php outputs, if you remove imagejpeg() and don't send the image headers. This will give you the necessary information.

Categories