display image uploaded - php

So I have this code. I am working with uploading image and I want it to be displayed after the user has uploaded it. Help me with my code please, just a PHP newbie here. :(
connect.php
<?php
$servername = "localhost";
$user = "root";
$password = "12345";
$db = "demo";
$con = mysqli_connect($servername, $user, $password, $db);
if (!$con) {
die('Could not connect: ' .mysql_error());
}
?>
try.php here
<?php include 'connect.php'; ?>
<?php
if (isset($image)) {
$errors = array();
$imageName = $_FILES['photoUpload']['name'];
$imageSize = $_FILES['photoUpload']['size'];
$imageType = $_FILES['photoUpload']['type'];
$imageTmp = $_FILES['photoUpload']['tmp_name'];
$imageExt = strtolower(end(explode('.', $imageName)));
$expensions = array("jpeg", "jpg", "png");
if(in_array($imageExt, $expensions)===false) {
$errors[] = "Extensions not allowed. Only JPEG, JPG, PNG";
}
if($imageSize > 2097152) {
$errors[] = "File size must not exceed 2MB";
} else { print_r($errors); }
}
?>
<div class="col-md-4">
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="photoUpload"><br><br>
<input type="submit" name="submit" value="SUBMIT"/>
<ul>
<li>Sent File: <?php echo $imageName; ?></li>
<li>File Size: <?php echo $imageSize; ?></li>
</ul>
</form>
</div>
I know I lack something here like displaying it using echo and such. I also want it to be displayed in height & width = 200px; and border-radius: 50%;

Are you saving the name of it in your database?
If so, try this below
$id = $_SESSION['id'];
$sql = "SELECT image FROM user WHERE `id` = $id";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
//img tag fetching from folder 'images' - change to match the file it was uploaded to
echo "<img src='images/".$row['image']."' style='width:30%; height:30%;'>";
echo "</div>";
}
You will need to change the query to fit your code, but the idea should set you in the right direction.

Related

PHP / MySQL: Image successfully save to database but failed to display at web page

I have a very weird problem in my system. I already create a system to upload the image to the database and display it. The problem is, the image is successfully uploaded but, it will return the message "Failed to upload!". Then, the picture that had been uploaded does not display. Below is my code:
<body>
<div class="wrapperDiv">
<form action="" method="post" id="form" enctype="multipart/form-data">
Upload image :
<input type="file" name="uploadFile" value="" />
<input type="submit" name="submitBtn" value="Upload" />
</form>
<?php
$last_insert_id = null;
include('db2.php');
if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn'])) {
if(isset($_FILES['uploadFile']['name']) && !empty($_FILES['uploadFile']['name'])) {
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png","gif");
//File extension
$ext = strtolower(pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION));
//Check extension
if(in_array($ext, $allowed_extensions)) {
//Convert image to base64
$encoded_image = base64_encode(file_get_contents($_FILES['uploadFile']['tmp_name']));
$encoded_image = $encoded_image;
$query = "INSERT INTO tbl_images SET encoded_image = '".$encoded_image."'";
$sql = $conn->prepare($query);
$sql -> execute();
//$results = $sql -> fetchAll(PDO::FETCH_OBJ);
echo "File name : " . $_FILES['uploadFile']['name'];
echo "<br>";
if($sql->rowCount() > 1 ) {
echo "Status : Uploaded";
$last_insert_id = $conn-> lastInsertId();
} else {
echo "Status : Failed to upload!";
}
} else {
echo "File not allowed";
}
}
if($last_insert_id) {
$query = "SELECT encoded_image FROM tbl_images WHERE id= ". $last_insert_id;
$sql = $conn->prepare($query);
$sql -> execute();
if($sql->rowCount($sql) == 1 ) {
//$row = mysqli_fetch_object($result);
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo "<br><br>";
echo '<img src="'.$row->encoded_image.'" width="250">';
}
}
}
}
?>
</div>
</body>
Can someone help me? Thanks!
you doing some thing wrong first you encoded the image when store in database so you must decode it again, and the src in tag get a url not image content just echo the content like this:
header('Content-type: image/jpeg');
echo base64_decode($row->encoded_image);
or
<img src="data:image/png;base64,'.$row->encoded_image.'" width="250">
but at all, store images in database is not a good option, your database become too heavy and can't respond fast and get too memory you can just store the image name in database and move the file form special place in your server the you can show like this.
echo '<img src="specialRoot/'.$row->image_name.'" width="250">';
Store images in folder..
I have created uploads folder in root, you can create folder at anywhere and write your path while fetching the image..
<body>
<div class="wrapperDiv">
<form action="" method="post" id="form" enctype="multipart/form-data">
Upload image :
<input type="file" name="uploadFile" value="" />
<input type="submit" name="submitBtn" value="Upload" />
</form>
<?php
$last_insert_id = null;
include('db2.php');
if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn'])) {
if(isset($_FILES['uploadFile']['name']) && !empty($_FILES['uploadFile']['name'])) {
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png","gif");
$name = $_FILES['uploadFile']['name'];
$target_dir = "uploads/"; //give path of your folder where images are stored.
$target_file = $target_dir . basename($_FILES["uploadFile"]["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//Check extension
if( in_array($imageFileType,$allowed_extensions) ){
//Convert image to base64
$image_base64 = base64_encode(file_get_contents($_FILES['uploadFile']['tmp_name']) );
$encoded_image = 'data:image/'.$imageFileType.';base64,'.$image_base64;
//$encoded_image = base64_encode($_FILES['uploadFile']['tmp_name']);
//$encoded_image = $encoded_image;
$query = "INSERT INTO tbl_images SET encoded_image = '".$encoded_image."'";
$sql = $conn->prepare($query);
$result = $sql -> execute();
move_uploaded_file($_FILES['uploadFile']['tmp_name'],$target_dir.$name);
echo "File name : " . $_FILES['uploadFile']['name'];
echo "<br>";
if($result == 1) {
echo "Status : Uploaded";
$last_insert_id = $conn->insert_id;
} else {
echo "Status : Failed to upload!";
}
} else {
echo "File not allowed";
}
}
if($last_insert_id) {
$query = "SELECT encoded_image FROM tbl_images WHERE id= ". $last_insert_id;
$result = $conn->query($query);
while($row = $result->fetch_assoc()){
echo '<img src="'.$row['encoded_image'].'" width="250">';
}
}
}
?>
</div>
</body>

Cant Display Image From Mysql tried so many solution nothing seem to work

following is the code i used to display image from database which is in long blob format.
upload.php:
if(isset($_FILES['files'])){
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "photost";
$conn=mysqli_connect($servername, $username, $password, $dbname);
$user_id=$_POST['user_id'];
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$errors="";
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
$file_content = file_get_contents($file_tmp);
$maxsize = 10000000;
if($_FILES['files']['tmp_name'][$key]==UPLOAD_ERR_OK) {
if(is_uploaded_file($_FILES['files']['tmp_name'][$key])) {
if( $_FILES['files']['tmp_name'][$key] < $maxsize) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
if(strpos(finfo_file($finfo, $_FILES['files']['tmp_name'][$key],"image"))==0) {
$imgData = addslashes(file_get_contents($_FILES['files']['tmp_name'][$key]));
$query="INSERT INTO `images`(`id`, `u_id`, `image`, `status`, `file_name`, `file_size`) VALUES ( NULL,'$user_id','{$imgData}',0,'$file_name','$file_type');";
if (mysqli_query($conn, $query)) {
echo "New record created successfully";
} else {
echo "Error: <br>" . mysqli_error($conn);
}
else
echo "<p>Uploaded file is not an image.</p>";
}
}
}
}
}
<body>
<div style="width:100%;height:40%">
</div>
<div align=center>
<form action="" method="POST" enctype="multipart/form-data">
<table style="width:40%">
<tr>
<th align="left">User Id:</th>
<th align="left"><input type='text' name='user_id'></th>
</tr>
<tr>
<th></th>
<th align="left"><input type="file" name="files[]" multiple/></th>
</tr>
<tr>
<th></th>
<th ><input type="submit"/></th>
</tr>
</table>
</form>
</div>
</body>
test.php:
<body>
<img src="getImage.php?id=1" />
</body>
getImage.php:
<?php
$id = $_GET['id'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "photost";
$conn=mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$query="SELECT * FROM `images` WHERE `id`=$id";
$result =mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$image =$row['image'];
/** check if the image is db */
if($image!=null)
{
$db_img = imagecreatefromstring($image);
Header("Content-type: image/jpeg");
imagejpeg($db_img);
}
mysql_close($conn);
?>
i also tried this one:
$row = mysql_fetch_assoc($result);
header("content-type: image/jpeg");
echo $row['image'];
mysql_close($conn);
im getting output like this
https://i.stack.imgur.com/RDkdM.png
one more thing i can see image by downloading it from phpmyadmin and saving it in jpeg format.
mysqli_fetch_assoc function returned arrays of each row.
Now try
$image = $row[0]['image'];
instead:
$image = $row['image'];

how do I display on my webpage an image file stored in my mysql database?

Can someone please help as I am at a loss. How can I get an image from MYSQL database onto my webpage. anyname.html
Database name is: upload
Table name is: images
id Primary int(11) AUTO_INCREMENT
name varchar(100)
size int(11)
type varchar(20)
content mediumblob
The upload works great but just cant get it to show the image of be able to use it in a html page. When I upload the image I get as a return: for number 11 image stored but I don't see an image: Here is my code, so please, please someone help as I have been at this for ages with no result.
my upload.php code:
<?php
// Check for post data.
if ($_POST && !empty($_FILES)) {
$formOk = true;
//Assign Variables
$path = $_FILES['image']['tmp_name'];
$name = $_FILES['image']['name'];
$size = $_FILES['image']['size'];
$type = $_FILES['image']['type'];
if ($_FILES['image']['error'] || !is_uploaded_file($path)) {
$formOk = false;
echo "Error: Error in uploading file. Please try again.";
}
//check file extension
if ($formOk && !in_array($type, array('image/png', 'image/x-png', 'image/jpeg', 'image/pjpeg', 'image/jpg', 'image/gif'))) {
$formOk = false;
echo "Error: Unsupported file extension. Supported extensions are JPG / PNG.";
}
// check for file size.
if ($formOk && filesize($path) > 500000) {
$formOk = false;
echo "Error: File size must be less than 500 KB.";
}
if ($formOk) {
// read file contents
$content = file_get_contents($path);
//connect to mysql database
if ($conn = mysqli_connect('localhost', 'root', '', 'upload')) {
$content = mysqli_real_escape_string($conn, $content);
$sql = "insert into images (name, size, type, content) values ('{$name}', '{$size}', '{$type}', '{$content}')";
if (mysqli_query($conn, $sql)) {
$uploadOk = true;
$imageId = mysqli_insert_id($conn);
} else {
echo "Error: Could not save the data to mysql database. Please try again.";
}
mysqli_close($conn);
} else {
echo "Error: Could not connect to mysql database. Please try again.";
}
}
}
?>
<html>
<head>
<title>Upload image to mysql database.</title>
<style type="text/css">
img{
margin: .2em;
border: 1px solid #555;
padding: .2em;
vertical-align: top;
}
</style>
</head>
<body>
<?php if (!empty($uploadOk)): ?>
<div>
<h3>Your Image has been Uploaded:</h3>
</div>
<div>
<img src="image.php?id=<?=$imageId ?>" width="300px" height="300px"></img>
<strong><br /><br />Embed</strong>: <input size="30" value='<img src="image.php?id=<?=$imageId ?>">'>
</div>
<hr>
<?php endif; ?>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data" >
<div>
<h3>Image Upload:</h3>
</div>
<div>
<label>IMAGE SELECT<br /></label>
<input type="hidden" name="MAX_FILE_SIZE" value="500000">
<input type="file" name="image" />
<br /><br />
<input name="submit" type="submit" value="Upload Image">
</div>
</form>
</body>
</html>
It seems to be a duplicate from the issue there PHP display image BLOB from MySQL
Hope it helps.
If you store the image data in database, use the next image.php:
<?php
$id = $_GET['id'];
$link = mysql_connect('localhost', 'root', '');
mysql_select_db('upload');
$sql = "SELECT content FROM images WHERE id=$id";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['content'];
?>

ajax php sql without refreshing

I'm not familiar with ajax and I'm trying to submit a form using one PHP page and ajax so that after form is submitted/updated the page doesn't refresh completly. the php page is loaded on a div section of a parent page.
Can someone point me in the right direction how to submit the form without refreshing the entire page?
Below the code I have so far, and it is only all in one php file. Thank you
<?php
$servername = "data";
$username = "data";
$password = "data";
$database = "data";
$successAdd="";
$errorAdd="";
$connect = mysql_connect($servername, $username, $password) or die("Not Connected");
mysql_select_db($database) or die("not selected");
if (isset($_POST['Add'])) {
$venueName = $_POST['cname'];
$file = $_FILES['file'];
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('png');
if (in_array($file_ext, $allowed)) {
if ($file_error == 0) {
$file_name_new = $venueName . '.' . $file_ext;
$file_destination = 'images/category/' . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$sql = "INSERT INTO `categorytable`(`category`) VALUES ('$venueName')";
$result = mysql_query($sql, $connect);
if ($result != 0) {
$successAdd = "Success fully done";
} else {
$errorAdd = "Not done ";
}
}
} else {
$errorAdd = "Something is wrong";
}
} else {
$errorAdd = "Only png file allowed";
}
}
if (isset($_POST['Update'])) {
$venueName = $_POST['cname'];
$file = $_FILES['file'];
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('png');
if (in_array($file_ext, $allowed)) {
if ($file_error == 0) {
$file_name_new = $venueName . '.' . $file_ext;
$file_destination = 'images/category/' . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$successAdd = "Success fully done";
}else{
$errorAdd = "Not Updated";
}
} else {
$errorAdd = "Something is wrong";
}
} else {
$errorAdd = "Only png file allowed";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<h3 style="color: red"><?php echo $errorAdd; ?></h3>
<h3 style="color: green"><?php echo $successAdd; ?></h3>
<!--<div style="float: left;width: 50%">-->
<h1>Add Category</h1>
<form action="" method="POST" enctype="multipart/form-data" id="add-category" >
Category Name <input type="text" name="cname" value="" /><br/>
Category Image <input type="file" name="file" accept="image/x-png"/><br/>
<input type="submit" value="Add" name="Add"/>
</form>
<!--</div>-->
<!--<div style="float: left;width: 50%">-->
<h1>Update Category</h1>
<form action="addCategory.php" method="POST" enctype="multipart/form-data" >
Select Category<select name="cname">
<?php
$sql = "SELECT * FROM `categorytable`";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
?>
<option value="<?php echo $row[1]; ?>"><?php echo $row[1]; ?></option>
<?php } ?>
</select><br/>
Category Image <input type="file" name="file" accept="image/x-png"/><br/>
<input type="submit" value="Update" name="Update"/>
</form>
<!--</div>-->
<div style="width: 25%;margin: 20px auto;float: left">
<table border="1">
<tr>
<th>Category Name</th>
<th>Category Image</th>
</tr>
<?php
$sql = "SELECT * FROM `categorytable`";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
?>
<tr>
<td><?php echo $row[1]; ?></td>
<td>
<img src="images/category/<?php echo $row[1]; ?>.png" height="50"/>
</td>
</tr>
<?php
}
?>
</table>
</div>
</body>
First things first, swap to PDO, ASAP. This will save you TONS of time and can help with SQL execution time, when used correctly (You can find a quick PDO tutorial here). To answer question, I would recommend you start with importing the jQuery library. It allows near effortless manipulation of the DOM.
Then, just do something like
$('#your-form-id-here').submit(function(clickEvent){
$.ajax({
url: 'http://www.foo.com/',
data: $('#your-form-id-here').serialize(),
method: 'POST',
success: function(Response){
//If the request is successful, this code gets executed
},
error: function(){
//If the request failed, this code gets executed
}
});
return false; <----This prevents the page from refreshing
});
Now lets break it down a bit
data: $('#your-form-id-here).serialize() <-- This gets all of your form data ready
NOTE: There's way more to it than this. You'll need to do some server-side stuff to make this work right. For instance, if you want a JSON object back, you'll need to return it. In php, I like to do something like
if(My request succeeded){
echo(json_encode(array(
'status' => 'success',
'message' => 'Request description/whatever you want here'
)));
}

fatal error function must be a string

<?php
if(isset($_POST['submit'])){
mysql_connect('localhost','root','');
$con_db=mysql_select_db('test');
if(!$con_db)echo"Error Connecting";
$imageName = mysql_real_escape_string($_FILES['image']['name']);
$imageData = mysql_real_escape_string(file_get_contents($_FILES['image']['tmp_name']));
$imageType = mysql_real_escape_string($_FILES['image']['type']);
echo $imageName;
if(substr($imageType,0,5)=="image"){
mysql_query('insert into image values("","$imageData","imageName")');
}
else echo "Select Image to Post";
}
?>
<body>
<form action="" method="post" enctype="multipart/form-data">
<table>
<td><tr>Upload image</tr><td><input type="file" name="image"></td>
<td><tr></tr><tr><input type="submit" name="submit"></tr></td>
</table>
I here have created a form and tried to upload the pic it got uploaded when i try to show the uploaded image its showing that there is a fatal error function must be a string
<?php
$my_con=mysql_connect('localhost','root','');
mysql_select_db('test');
$getid = $_GET('id');
if(isset($getid)){
$id = $getid;
$db_query = mysql_query("select * from 'image' where id='$id'");
while($row = mysql_fetch_row($db_query)){
$imageData = $row['image'];
}
header("content-type: image");
}
else{
echo "Error!";
}
?>
This is another php file to display the image

Categories