Default image won't show when database is still empty - php

Basically, the whole thought here is changing profile pictures and it will be uploaded in the database.
I want to show a default icon first when the database is still empty but my codes just displays a broken image thumbnail. What could have gone wrong?
<form method="post" enctype="multipart/form-data">
<div class="row form-group">
<div class="col col-md-3">
<label for="text-input" class="form-control-label">Profile Picture</label>
</div>
<div class="col-9 col-md-9">
<div class="input-group">
<?php
$query = "SELECT image FROM member WHERE member_id = '$ID'";
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result))
{
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['image']).'">';
}
} else{
echo "<img src='images/icon.jpg' style='height:200px'draggable='false'>";
}
?>
<div class="col-12">
<input type="file" name="image" id="image" style ='margin-left:-10px;margin-top:5px'>
</div>
<div class="col-12">
<input type="submit" name="insert" id="insert" value="Change Profile Picture" class="btn btn-primary" style ='margin-left:-10px;margin-top:5px'>
</div>
<?php
if(isset($_POST["insert"])){
$file = addslashes(file_get_contents($_FILES["image"]["tmp_name"]));
$query = "UPDATE member SET image = '$file' WHERE member_id='$ID'";
if(mysqli_query($con, $query)){
echo ("<script LANGUAGE='JavaScript'>
window.alert('Profile Picture has been successfully changed!');
window.location.href='edit.php';
</script>");
}
}
?>
</div>
</div>
</div>
</form>

if your database is empty upload query will not work. if your image row is empty then your code should be like if image row is not empty display image else display the default image.
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)) {
if (isset($row['image']) && !empty($row['image'])) {
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['image']).'">';
} else {
echo "<img src='images/icon.jpg' style='height:200px'draggable='false'>";
}
} // endwhile
} else{
echo "no result found";
}

While writing HTML or CSS code inside PHP you should put a \ before all double quotations and you need change all quotations to double quotation.like shown below:
echo "<img src=\"images/icon.jpg\" style=\"height:200px;\" draggable=\"false\">";
I didn't check your PHP codes, If you've coded them properly the problem is obviously what I mentioned.

Related

how to prevent data empty in db when no file upload on editing that file in php

Let me explain my problem briefly.I have image names in MYSQL database.
I need to change the image name when user uploads a new image using file input field.Otherwise the image name in database remain same.But My problem is when user doesn't upload any images the image name becomes empty in database.
My HTML code for changing a image
<form method="post" action="edit_store_img.php?id=<?php echo (int)$store['id'] ?>" class="clearfix" enctype="multipart/form-data">
<div class="form-group">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-th-large"></i>
</span>
<label for="file">Upload a store image</label>
<input type="file" name="storepic" value="<?php echo $store['pic']; ?>"/>
</div>
</div>
<hr>
<br>
<h3>Change Map Image For Store <?php echo remove_junk($store['name']);?></h3>
<hr>
<!-- below code is for map image -->
<?php if($store['pic'] === '0'): ?>
<img class="img-avatar img-circle" src="uploads/mapimg/no_image.jpg" alt="Store_map_picture" style="width: 200px;height: 200px;">
<?php else: ?>
<img class="img-avatar img-circle" src="uploads/mapimg/<?php echo $store['map']; ?>" alt="Store_map_picture" style="width: 200px;height: 200px;">
<?php endif;
?>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-th-large"></i>
</span>
<label for="file">Upload a Store map location image</label>
<input type="file" name="mappic" value="<?php echo $store['map']; ?>"/>
</div>
</div>
<div class="col-md-12">
<button type="submit" name="edit_store_img" class="add-btn">Update Store image</button>
</div>
</form>
This is my PHP file for getting ID for that particular image
<?php
$store = find_by_id('store',(int)$_GET['id']);
if(!$store)
{
$session->msg("d","Missing store id.");
redirect('store.php');
}
?>
This is my PHP code for Storing image name in database
<?php
if(isset($_POST['edit_store_img']))
{
if(empty($errors))
{
/*below queries is for image upload */
$msg = "";
$map = $_FILES["mappic"]["name"];
$tempname = $_FILES["mappic"]["tmp_name"];
$mapfolder = "uploads/mapimg/".$map;
// Now let's move the uploaded image into the mapfolder: image
if (move_uploaded_file($tempname, $mapfolder)) {
$msg = "map Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
$message = "";
$pic = $_FILES["storepic"]["name"];
$tempname = $_FILES["storepic"]["tmp_name"];
$picfolder = "uploads/storeimg/".$pic;
// Now let's move the uploaded image into the folder image
if (move_uploaded_file($tempname, $picfolder)) {
$message = "Image uploaded successfully";
}else{
$message = "Failed to upload image";
}
$query = "UPDATE store SET";
$query .=" map ='{$map}', pic ='{$pic}'";
$query .=" WHERE id ='{$store['id']}'";
$result = $db->query($query);
if($result && $db->affected_rows() === 1){
$session->msg('s',"store updated ");
redirect('store.php', false);
} else {
$session->msg('d',' Sorry failed to updated!');
redirect('edit_store_img.php?id='.$store['id'], false);
}
}
else
{
$session->msg("d", $errors);
redirect('edit_store_img.php?id='.$store['id'], false);
}
}
?>
I Need to store image name when user doesn't upload image.I need to avoid the image name db field becomes empty.
Below quirky will somehow fix your problem; however, this is not the correct way I think;
$query .=" map = IF('{$map}' != '', '{$map}', map), pic = IF('{$pic}' != '', '{$pic}', pic)";
We are just asking the database to update with the exiting column value if the passed value is empty.
The correct way should be not to take it for granted that the user have uploaded a file; as you are doing with these below lines in your code;
$map = $_FILES["mappic"]["name"];
...
$pic = $_FILES["storepic"]["name"];
You should be actually using IF conditions to check if some viable value has been set for those _FILES variables so you know what to process for and what not, and prepare your SQL UPDATE statement accordingly.

I have a problem in displaying images from database to page

I have created a website with an upload feature for gallery.
The upload works flawless,but it doesn't shows the images on the webpage.
I can not find the error in the code
I have tried to display the image as a background-image for the box I created and with an image tag with the attribute src.
The last method shows me that the website is reading the image but it can not be displayed.
<div class="wrapper">
<h2>Art Gallery</h2>
<div class="Gallery-container">
<?php
include_once 'includes/dbh.inc.php';
$sql = "SELECT * FROM gallery1 ORDER BY orderGallery DESC";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed!";
} else{
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
echo '<a href="#">
<div><img src=url(gallery/img/'.$row["imgfullnameGallery"].');></div>
<h3>'.$row["titleGallery"].'</h3>
<p>'.$row["descGallery"].'</p>
</a>';
}
}
?>
</div>
<?php
if (isset($_SESSION['username'])) {
echo '<div class="gallery-upload">
<form action="includes/galleryupload.inc.php" method="post" enctype="multipart/form-data">
<input type="text" name="filename" placeholder="File name...">
<input type="text" name="filetitle" placeholder="Title...">
<input type="text" name="filedesc" placeholder="Description...">
<input type="file" name="file">
<button type="submit" name="submit">UPLOAD</button>
</form>
</div>';
}
?>
</div>
You have used the wrong syntax img tag
please update below code
while ($row = mysqli_fetch_assoc($result)) {
echo '<a href="#">
<div><img src="gallery/img/'.$row["imgfullnameGallery"].'"></div>
<h3>'.$row["titleGallery"].'</h3>
<p>'.$row["descGallery"].'</p>
</a>';
}

I want to update the values but i dont want to change image when i update image is remove

I am updating my form values . Image is already uploaded and can see on the form. When i only update the text value the image is remove and it showing blank.means it does not remains the same when i update it just remove automatically i think not getting the path for current image value when i updating other values. kindly help me to sort out this problem
like if i have to update only name of the person i change the name and other fields remains same. When i click on update all values remains same and also update one which i update but problem is this photo is remove not remain same
<?php
$v_id = $_GET['v_id'];
include "config.php";
$sql = "SELECT * FROM my_veh_ven WHERE v_id='$v_id'";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result)) {
?>
<!-- form start -->
<form role="form" method="POST" action="updateVehicle.php?v_id=<?= $row["v_id"] ?>" enctype="multipart/form-data">
<div class="box-body">
<div class="form-group col-md-offset-0 col-md-4">
<label for="">25+ Days Rent in PKR</label>
<input type="text" class="form-control" name="v_25_plus_rent" value="<?=$row["v_25_plus_rent"]?>">
</div>
<div class="form-group col-md-offset-0 col-md-8">
<label >Change Vehicle Picture</label>
<input type="file" name="image" id="myFile" value="images/<?=$row["image"]?>" accept="image/*">
</div>
<div class="form-group col-md-offset-0 col-md-4" style="text-align: center;">
<label for="exampleInputFile" style="text-align: center;" >Current Vehicle Picture</label>
<?php echo'<Image src="images/'.$row["image"].'" style="width:325px;height:220px;"></Image>'; ?>
</div>
<div class=" ">
<div class=" with-border" style="text-align:center;">
<h4 class="box-title" style="text-align:center;"><b>Vendor Details</b></h4>
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer skin-yellow">
<button type="submit" name="submit" class="btn btn-primary skin-yellow">Update</button>
</div>
</form>
<?php
}
} else {
echo "Sorry something wrong";
}
mysqli_close($conn);
?>
updating file
<?php
include "config.php";
if(isset($_POST['submit']))
{
$target = "images/".basename($_FILES['image']['name']);
$v_type = $_POST["v_type"];
$v_name = $_POST["v_name"];
$v_man = $_POST["v_man"];
$v_model = $_POST["v_model"];
$v_color = $_POST["v_color"];
$v_trans = $_POST["v_trans"];
$v_1_15_rent = $_POST["v_1_15_rent"];
$v_16_25_rent = $_POST["v_16_25_rent"];
$v_25_plus_rent = $_POST["v_25_plus_rent"];
$v_reg = $_POST["v_reg"];
$vendor_name = $_POST["vendor_name"];
$vendor_mobile = $_POST["vendor_mobile"];
$vendor_price = $_POST["vendor_price"];
$image = $_FILES["image"]["name"];
$v_id=$_GET["v_id"];
$sql = " UPDATE my_veh_ven SET v_type='$v_type', v_name='$v_name' ,v_man='$v_man' ,v_color='$v_color', v_trans='$v_trans', v_1_15_rent='$v_1_15_rent' , v_16_25_rent='$v_16_25_rent' ,v_25_plus_rent='$v_25_plus_rent' , image='$image' , v_reg='$v_reg' ,vendor_name='$vendor_name', vendor_mobile='$vendor_mobile' ,vendor_price='$vendor_price' WHERE v_id='$v_id' ";
if (mysqli_query($conn, $sql))
{
if(move_uploaded_file($_FILES['image']['tmp_name'], $target))
{
$success = "✓ Successfully Updated";
}
}
else
{
$fail = "X Not Updated";
}
}
mysqli_close($conn);
?>
Simple Solution while adding put your image name in 1 hidden variable like below
$hiddenImage = $row["image"]
add this hidden variable in your form
<input type='hidden' name='hiddenImage' value='<?php echo $hiddenImage ?>'
and while submit check whether your file input type will contain any data or not. If data/image exist upload this image in folder and same name in db. if image not exist get that input variable save in database.
for e.g :
if (isset($_FILES["image"]["tmp_name"]) && $_FILES["image"]["tmp_name"] != "") {
// upload file and save image name in variable like $imagename
}else{
// if image not upload this code will execute
$imagename = $_POST['hiddenImage'];
}
Save this $imagename variable data in database
An <input type="file"/> has no value attribute usage. The image, once uploaded, is on your server and that's about it. You cannot set the value of the input to anything that would be meaningful.
What you certainly want is to display the uploaded picture instead of the input, and present the input if the user wants to change it.
EDIT: Now that we have your PHP code, we can see that you are overwriting the $image variable even if empty
$image = $_FILES["image"]["name"];
You have to verify if $_FILES["image"] exists, else image will be null or undefined. And then you will update the database with a bad value. I suggest you treat your upload differently than other data:
<?php
include "config.php";
if(isset($_POST['submit']))
{
$target = "images/".basename($_FILES['image']['name']);
$v_type = $_POST["v_type"];
$v_name = $_POST["v_name"];
$v_man = $_POST["v_man"];
$v_model = $_POST["v_model"];
$v_color = $_POST["v_color"];
$v_trans = $_POST["v_trans"];
$v_1_15_rent = $_POST["v_1_15_rent"];
$v_16_25_rent = $_POST["v_16_25_rent"];
$v_25_plus_rent = $_POST["v_25_plus_rent"];
$v_reg = $_POST["v_reg"];
$vendor_name = $_POST["vendor_name"];
$vendor_mobile = $_POST["vendor_mobile"];
$vendor_price = $_POST["vendor_price"];
$v_id=$_GET["v_id"];
$sql = " UPDATE my_veh_ven SET v_type='$v_type', v_name='$v_name' ,v_man='$v_man' ,v_color='$v_color', v_trans='$v_trans', v_1_15_rent='$v_1_15_rent' , v_16_25_rent='$v_16_25_rent' ,v_25_plus_rent='$v_25_plus_rent' , v_reg='$v_reg' ,vendor_name='$vendor_name', vendor_mobile='$vendor_mobile' ,vendor_price='$vendor_price' WHERE v_id='$v_id' ";
if (mysqli_query($conn, $sql))
{
if(move_uploaded_file($_FILES['image']['tmp_name'], $target))
{
$image = $_FILES["image"]["name"];
$success = "✓ Successfully Updated";
$sql = "UPDATE my_veh_ven SET image='$image' WHERE v_id='$v_id' ";
mysqli_query($conn, $sql)
}
}
else
{
$fail = "X Not Updated";
}
}
mysqli_close($conn);
?>
There's a simple solution for your problem. Whenever a form submits, check if $_FILES is set/any file is provided or not. If any file/image is provided, then update your database according to it. If the $_FILES array is empty, that means your image/file is not uploaded, and hence you can update it accordingly.
Something like below:
<?php
if(isset($_POST['submit'])){
//check for files or updated variables
if(isset($_FILES)){
//image is provided, now update values accrodingly in your database
echo "image/file provided";
}else{
//image is not uploaded, update other values in database expect image/file
echo "image/file not provided";
}
}else{
?>
<html>
<head><title>My demo form</title></head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
<input type="text" name="data_one">
<input type="file" name="my_file" accept="image/*">
<input type="submit" value="submit">
</body>
</html>
<?php
}
?>

Can't upload file in BLOB to the database, Directory issues in PHP

I'm having difficulties to insert the value as blob type always empty and the other method can't insert the images in a folder. Please you can show the way out. Thanks! This code is to save the image in a folder and then access it with the name to display, but is not saving the photos to the folder. I edited and include the form here, containing JavaScript and css .It looks some how messy but i'm a beginner. Thanks.
<?php
include("../views/post_form.php");
require("../includes/include.php");
require("../includes/sess_n.php");
if ($_SERVER["REQUEST_METHOD"]== "POST")
{
$usertext = $_POST["usertext"];
$image = $_FILES['image']['name'];
$talent =$_POST["talenttype"];
if(empty($usertext) || empty($image)|| empty($talent))
{
die();
}
$id = $_SESSION["id"];
$folder ="images/".basename($_FILES['image']['name']);
move_uploaded_file($_FILES['image']['tmp_name'],$folder) ;
$query = mysqli_query($link,"SELECT * FROM `upload` WHERE id = '$id'");
$upload = mysqli_query($link,"INSERT INTO `upload` (description,image,talent,folder) VALUES('$usertext','$image','$talent','$folder ')");
}
?>
To display, I want the photos to be save to the folder, not saving. I used blob method not inserting into the database.
<?php
include("../views/feeds_form.php");
require("../includes/include.php");
require("../includes/sess_n.php");
$query = mysqli_query($link,"SELECT * FROM `upload` ");
if ($query === false)
{
die();
}
echo '<table>';
while ($run = mysqli_fetch_assoc($query))
{
echo '<tr>';
echo '<td>';?> <img src =" <?php echo $run["image"]; ?>" height=100 width=100> <?php echo '<td>';
echo '<td>'; echo $run["description"]; echo '<td>'; echo $run["folder"];echo '<td>';
echo '</tr>';
}
echo '</table>';
?>
The form here.
<?php
include("../public/header.php");
?>
<div><title>post</title></div>
<style>
.form-inline
{
text-align: center;
margin-bottom: 50px;
}
</style>
<script type="text/javascript">
function validate(){
var usertext = document.getElementById("usertext");
var talent = document.getElementById("talenttype");
var image = document.getElementById("image");
if (usertext.value === "" && talent.value === "" && image.value ==="")
{
alert("Field Must Not be Empty");
}
}
</script>
<form class="form-inline" method ="POST" action ="post.php" enctype="multipart/form-data" onsubmit= "return validate();">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3"> </label>
<textarea class="form-control" id = "usertext" name ="usertext" rows="5" placeholder="Describe Person Here"></textarea> <br><hr>
<label class="sr-only" for="exampleInputEmail3"></label><br>
<div class="form-group">
<label for="exampleInputPassword1"></label>
<input type="file" class="form-control" id = "image" id="exampleInputPassword1" name="image" placeholder="image">
</div> <br><br><br> <hr>
<div class="form-group">
<label for="exampleInputPassword1"></label>
<input type="text" class="form-control" id = "talenttype" id="exampleInputPassword1" name = "talenttype" placeholder="Talent-Type"><br><br>
</div> <hr>
<div>
<button type="submit" name ="post" class="btn btn-default">Post</button><br>
</div>
</div>
</form>
<?php
include("../public/footer.php");
?>
I was having permission issues, the images folder permission was changed. That solves everything. Thanks!

Form with textarea and multiple files input option repeats the entry while uploading to database

I've form with two Text areas and a multiple file input field and I need to upload them to database ....
here is my HTML code
<form method="post" action="../php/new-upload.php" enctype="multipart/form-data">
<div id="tabs-1">
<textarea placeholder="Hi" name="n_head" class="n_head"></textarea>
<textarea placeholder="Story..." name="n_st" class="n_st"></textarea>
<div class="tg-it">
<div class="tg-it-hd">Add Tag:</div>
<input name="tags" id="singleFieldTags2" value="Election, Namo">
</div>
</div>
<div id="tabs-2" class="new-post-det">
<div id="upload">
<div id="drop">
Drop Images Here
or
<a>Browse</a>
<input type="file" name="upl[]" multiple />
</div>
<ul>
<!-- The file uploads will be shown here -->
</ul>
</div>
</div>
<div id="new-ps-bt">
<input type="submit" class="new-ps-bt" value="Post" />
<a id="bk-bt" class="bk-mn" href="../">Back <</a>
</div>
</form>
and here is my new-upload.php file
<?php
include("../config.php");
session_start();
$n_head=$_POST['n_head'];
$n_story=$_POST['n_story'];
$n_up=$_SESSION["user_id"];
$query = "INSERT INTO news(N_headline,N_story,N_U_id)VALUES('$n_head','$n_story','$n_up')";
$data = mysql_query ($query)or die(mysql_error());
$last_id = mysql_insert_id();
foreach ($_FILES['upl']['name'] as $filename) {
$n_img = $_FILES['upl']['tmp_name'];
$query_1 = "INSERT INTO news_img(N_id,ng_img)VALUES('$last_id','$n_img')";
$data_2 = mysql_query ($query_1)or die(mysql_error());
}
if($data)
{
header("Location:../");
}
mysql_close($con);
?>
so the problem is when this form is submitted, the database entry gets repeated the number of times same as the number of photos selected ....
help me out with this problem...
Please change these code in respective place
$n_story = $_POST['n_story'];
foreach ($_FILES['upl']['name'] as $filename) {
$n_img = $filename;
$query_1 = "INSERT INTO news_img(N_id,ng_img)VALUES('$last_id','$n_img')";
$data_2 = mysql_query ($query_1)or die(mysql_error());
}
Hope that fix your problem.

Categories