I want to update my profile image but I don't know how to update it. I successfully insert it into my database and folder but when user wants to update it So I don't know how to update this image. Can you tell me how this is possible? Thanks.
Code of my HTML form
<form class="form" action="accountsetting.php" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-12 col-sm-auto mb-3">
<div class="mx-auto" style="width: 140px;">
<div class="rounded-circle avatar avatar-xl mb-3">
<img class="rounded-circle" id="preview_avatar" name="avatar" src="<?php echo
$_SESSION['user']['avatar']; ?>" width="100" height="100">
</div>
</div>
</div>
<div class="col d-flex flex-column flex-sm-row justify-content-between mb-3">
<div class="text-center text-sm-left mb-2 mb-sm-0">
<h4 class="pt-sm-2 pb-1 mb-0 text-nowrap"><?php echo $_SESSION['user']['fullname']; ?></h4>
<p class="mb-0"><?php echo $_SESSION['user']['username']; ?></p>
<div class="form-group mb-2 pt-2">
<input class='input' type='hidden' name='id' value="<?php echo $_SESSION['user']['id']; ?>" />
<input id="avatar" type="file" name="avatar" hidden="" accept="image/png, image/jpeg,
image/jpg">
<button id="uploadBtn" type="submit" name="profile" class="btn btn-primary btn-file " ><i
class="fa fa-camera" aria-hidden="true"></i>   Upload Avatar</button>
</div>
<div class="row">
<div class="col d-flex justify-content-end pr-5">
<button class="btn btn-primary " type="submit" name="profileupdate">Save Changes</button>
</div>
</div>
</div>
</div>
</div>
</form>
Code of my PHP side
// sava image into directoray
$id="";
$filename = $avatar['name'];
$fileerror = $avatar['error'];
$filetmp = $avatar['tmp_name'];
$fileext = explode('.',$filename);
$filecheck = strtolower(end($fileext));
$fileextstored =array('png', 'jpg', 'jpeg');
$destinationfile = 'upload/';
$destinationfile = $destinationfile .$filename;
$destinationfile1 = 'userside/upload/';
$destinationfile1 = $destinationfile1 .$filename;
try {
//throw exception if can't move the file
if (!move_uploaded_file($filetmp, $destinationfile)) {
throw new Exception('Could not move file');
}
if(!copy ( $destinationfile , $destinationfile1 ))
{
throw new Exception('Could not move 2nd file');
}
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
// image insert
if(in_array($filecheck, $fileextstored))
{
$query = "INSERT INTO users (avatar) VALUES('$destinationfile')";
$displayquery = "select * from users where id= $id";
$displayquery = mysqli_query($db,$displayquery);
}
What's type of code i will use. When the user click on the save button the image will successfully update.
It looks like you need a condition in your INSERT INTO statement. Shouldn't you insert the avatar in the users table where id = $id?
Here:
"INSERT INTO users (avatar) VALUES('$destinationfile')";
Change to:
"INSERT INTO users (avatar) VALUES('$destinationfile') WHERE id = $id";
Update: if you're inserting the path to the image, then maybe you need to put the URL in with the image tag:
<!-- insert code for http or https:// -->
<img class="rounded-circle" id="preview_avatar" name="avatar" src="<?php echo "http://" . $_SERVER['SERVER_NAME'] . "/" . $_SESSION['user']['avatar']; ?>" width="100" height="100">
This relies on that path being valid and accessible from the server name, like http://localhost/uploads/image_name.jpg if the path is .../uploads/image_name.jpg. You can put the path in the session variable, then just add the image name on the end, e.g. $_SESSION['image_path'] = 'http://localhost/uploads/'.
Related
Im learn php,try develops a little blog for myself. I have a problem.When I pull information from the database, everything is displayed except the picture. In code i try save picture in img folder, there is an addition to the database, but there is no saving to the folder.And this is probably why there is no image output.
I ask for help. Sorry for my English. Thanks!
//AddPost
<?php
session_start();
require_once '../DB.php';
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['button-post'])) {
$error ='';
if (!empty($_FILES['img']['name'])){
$img = time() . "_" . $_FILES['img']['name'];
$fileTmpName = $_FILES['img']['tmp_name'];
$fileType = $_FILES['img']['type'];
$destination = "../img/" . $img;
if (strpos($fileType, 'image') === false) {
$error = "The uploaded file is not an image!!";
}else{
$result = move_uploaded_file($fileTmpName, $destination);
if ($result){
$_POST['img'] =$img ;
// tt( $img);
}else{
$error = " Error uploading image to server";
}
}
}else{
$error= "Error getting picture";
}
$title = trim( $_POST['title']);
$texton = trim( $_POST['texton']);
if (strlen($title) <= 2 ) {
$error = '';
}
elseif (strlen($texton)<= 5 ) {
$error = '';
}
else {
$sql = "INSERT INTO `posts`(`title`, `texton`, `img`) VALUES(?,?,?)";
$query = $connect->prepare($sql);
$query->execute([$title,$texton,$img]);
}
}
//index
<?php
require_once 'DB.php';
$sql = "SELECT * FROM `posts` ORDER BY`id`DESC";
$query = $connect->query($sql);
while ($row = $query->fetch(PDO::FETCH_OBJ)):
?>
<div class="titlePost col-12 col-md-9">
<h2>
<?=$row->title;?>
</h2>
<div class="imgPost col-12 col-md-4">
<img src="/img .<?= $row->img?>;" alt="postik">
</div>
<p> <?=$row->texton;?></p>
</div>
<?php endwhile; ?>
<form action="addPost_form.php" method="post" class="row justify-content-center">
<h2>Add Post</h2>
<div class="mb-3 col-12 col-md-4 err">
<p><?=$error?></p>
</div>
<div class="w-100"></div>
<div class="mb-3 col-12 col-md-6">
<label for="title">Title</label>
<input type="text" name="title" id="title" class="form-control">
</div>
<div class="w-100"></div>
<div class="mb-3 col-12 col-md-8">
<label for="texton">Сontent</label>
<textarea type="text" name="texton" id="texton" class="form-control" ></textarea>
</div>
<div class="w-100"></div>
<div class="mb-3 col-12 col-md-4">
<input name="img" enctype='multipart/form-data' type="file" class="form-control" id="img">
</div>
<div class="w-100"></div>
<div class="mb-3 col-12 col-md-4">
</div>
<div class="w-100"></div>
<div class="mb-3 col-12 col-md-4">
<button type="submit" class="btn btn-secondary" name="button-post">Add</button>
</div>
</form>
You don't need to use ../img; instead of just using /img, it will point out your root directory then the img folder. Another thing make sure $imgName has the image extension. If not, then concatenate the image extension with it. And it would be best if you stored the image extension on the database to read the image successfully. If image src directly does not print the image name and extension, you can store it separate variable, for example, $image = $imgName.'.'.$imgExt in this way.
Hi I'm trying to store image into database using session and its successfully done but problem is that its can't display on my webpage when I upload the page and click on save button the previous pic display again but the new pic save into database successfully and I want to store the pic on my folder also the coding is as following
The Html page coding is as following
<form class="form" action="accountsetting.php" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-12 col-sm-auto mb-3">
<div class="mx-auto" style="width: 140px;">
<div class="rounded-circle avatar avatar-xl mb-3">
<img class="rounded-circle" id="preview_avatar" name="image" src="https://imgbob.com/path/cdn/avatars /zxMvnv1q52hFyNeEGKz0UuPU5fkth5YadkXe3m26S4HODj09An.png"
width="100" height="100">
</div>
</div>
</div>
<div class="col d-flex flex-column flex-sm-row justify-content-between mb-3">
<div class="text-center text-sm-left mb-2 mb-sm-0">
<h4 class="pt-sm-2 pb-1 mb-0 text-nowrap"><?php echo $_SESSION['user']['fullname']; ?></h4>
<p class="mb-0"><?php echo $_SESSION['user']['username']; ?></p>
<div class="form-group mb-2 pt-2">
<input class='input' type='hidden' name='id' value="<?php echo $_SESSION['user']['id']; ?>" />
<input id="avatar" type="file" name="avatar" hidden="" accept="image/png, image/jpeg, image/jpg">
<button id="uploadBtn" type="button" class="btn btn-primary btn-file " >
<i class="fa fa-camera" aria-hidden="true"></i>   Upload Avatar
</button>
</div>
<div class="row">
<div class="col d-flex justify-content-end pr-5">
<button class="btn btn-primary " type="submit" name="profile">Save Changes</button>
</div>
</div>
</div>
</div>
</div>
</form>
The PHP coding is as following
$id = "";
if(isset($_POST['profile'])) {
$id = $_SESSION['user']['id'];
$file=addslashes(file_get_contents($_FILES["avatar"]["tmp_name"]));
$query = "UPDATE users SET avatar = '$file' WHERE id = '$id'";
$query_run = mysqli_query($db,$query);
if($query_run) {
echo '<script type = "text/javascript"> alert("image profile upload")</script>';
} else {
echo '<script type = "text/javascript"> alert("image profile not upload")</script>';
}
}
Session from HTML page side
<?php
include('../functions.php');
if (!isLoggedIn()) {
$_SESSION['msg'] = "You must log in first";
header("location: /uploadimg/loginform.php");
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['user']);
header("location: /uploadimg/loginform.php");
}
if(isset($_SESSION['success']))
{
echo $_SESSION['success'];
unset($_SESSION['success']);
}
if(isset($_SESSION['user']['fullname']))
{
}
?>
Session from PHP page side
<?php
session_start();
function isAdmin()
{
if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'admin' ) {
return true;
}else{
return false;
}
}
function isLoggedIn()
{
if (isset($_SESSION['user'])) {
return true;
}else{
return false;
}
}
I have an upload image to database code like this:
<form method="post" action="quanly.php" class="form-group justify-content-center" enctype="multipart/form-data">
<div class="custom-file mb-3">
<input type="file" class="custom-file-input" id="image" name="image">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
<div class="col text-center">
<button type="submit" name="submit" id="add_btn" class="btn btn-primary mb-2"> <i class="fas fa-plus"></i>Submit</button>
</div>
</form>
And the PHP code:
$image = addslashes($_FILES['image']['name']);
$query = "INSERT INTO tasks (image) VALUES ('$image')";
mysqli_query($db, $query); //db is the mysql connection
Everything upload works just fine, but I have some code to display image using Bootstrap 4 modal
<?php $i = 1; while ($row = mysqli_fetch_array($tasks)) { ?>
<button type="button" class="btn btn-primary btn-sm " data-toggle="modal" data-target="#imagemodal<?php echo $row['id'];?>" <?php if (empty($row['image'])) { echo "disabled"; } ?> ><i class="fas fa-image"></i></button>
<!-- IMAGE MODAL BEGIN -->
<div class="modal fade" id="imagemodal<?php echo $row['id'];?>">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Xem ảnh/ đính kèm</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<?php echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>'; ?>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- IMAGE MODAL END -->
<?php $i++; } ?>
Which image of rows showing a small image square (error), when I view the image url, it's something like this: data:image/jpeg;base64,ei5wbmc=
Store and upload image in folder code
<?php
if(isset($_POST['but_upload'])){
$name = $_FILES['file']['name'];
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
// Select file type
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif");
// Check extension
if( in_array($imageFileType,$extensions_arr) ){
// Insert record
$query = "insert into images(name) values('".$name."')";
mysqli_query($con,$query);
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);
}
}
?>
<form method="post" action="" enctype='multipart/form-data'>
<input type='file' name='file' />
<input type='submit' value='Save name' name='but_upload'>
</form>
Show in display view.
<?php
$sql = "select name from images where id=1";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
$image = $row['name'];
$image_src = "upload/".$image;
?>
<img src='<?php echo $image_src; ?>' >
I have a page in my clients dashboard for editing his about content.
Once i click on edit button it redirects to another page and there is an option for uploading new image and also content.
Problem :If no new image is uploaded suppose only some text fields are changed and clicked on update the text content changes and redirects to main page but image is deleted from db,but i don't want image to be deleted from the db if no new picture is uploaded.
Two Files Are there
1)index.php
2)editabout.php
index.php
<div class="main-container">
<div class="row">
<div class="container">
<div class="col-lg-12">
<div class="row">
<?php include('db.php'); $select=mysql_query("SELECT * FROM `about`"); while($row=mysql_fetch_array($select)){?>
<div class="col-md-3"><img id="profileimage" src="about/<?php echo $row['image']; ?>" style="width:100%;height:200px;" class="img-thumbnail img-responsive" required>
<div class="row">
<div class="col-md-6"> <input style="width:100%;" class="btn btn-info btn-lg mb-3 mr-3" type="submit" value="Edit"></div>
</div>
</div>
<?php}?>
</div>
</div>
</div>
</div>
editabout.php
<div class="row">
<div class="col-lg-4">
<form action="" method="post" enctype="multipart/form-data">
<div class="main-container file-upload">
<div class="file-upload__dropzone">
<?php
include('db.php');
$select=mysql_query("SELECT * FROM `about` where `sl.no`='$bid' ");
while($row=mysql_fetch_array($select)){
?>
<img id="profileimage" src="about/<?php echo $row['image']; ?>" value="<?php echo $row['image']; ?>" class="img-thumbnail img-responsive" style="width:100%;height:200px;">
<?php } ?>
<div class="file-upload__browse-files">
<button class="btn btn-outline-info btn-lg btn-block btn-rounded file-upload__browse-btn">Browse files</button>
<input id="upload-files-default" name="img" type="file" multiple class="upload" onchange="readURL(this);">
</div><br>
<button class="btn btn-success btn-lg mb-2 mr-3" name="ok" type="submit">Update</button>
</div>
</div>
</form>
</div>
Php code for uploading
include('db.php');
if(isset($_POST['ok']))
{
$photo=$_FILES['img']['name'];
$target_dir = "about/";
$location = $target_dir .$_FILES["img"]["name"];
move_uploaded_file($_FILES['img']['tmp_name'],$location);
$query1="UPDATE `about` SET `image`='$photo',
`up_date`=now()
WHERE `about`.`sl.no` ='$bid'";
mysql_query($query1);
You have to check does the file exist/uploaded or not before executing any query. As an example below:
if(is_uploaded_file($_FILES["img"]["tmp_name"] && file_exists($_FILES["img"]["tmp_name"])){
//update query with picture
//move_uploaded_file here
}else{
//Only query updating does details without move_uploaded_file
}
Above code must be put in the if(isset($_POST["ok"])) code block.
I want to update image in one by one.
Example : I want to update only IMG1.
img1 : img_id = 1, img_name = demo1.jpg
img2 : img_id = 2, img_name = demo2.jpg
When I press update button with only IMG1 it should send img_id = 1 to $id = $_POST['image_id']; But it send img_id = 2 Then will make IMG2 has been update not IMG1.
updateimage.php
<div class="col-md-4 col-sm-6 col-xs-12">
<div class="text-center">
<?php $result = mysql_query("SELECT img_id, img_name FROM fm_product_image WHERE p_id_img = '$ID'")or die(mysql_error()); ?>
<?php while ($imagerows = mysql_fetch_array($result)) { $imgid = $imagerows['img_id']; ?>
<img class="avatar img-circle img-thumbnail" style="border-radius: 2px; width: 70%;" src="upload/<?php echo $imagerows['img_name']; ?>">
<h6>Upload your product image.</h6>
<input type="file" name="image" class="text-center center-block well well-sm">
<input type="text" required value="<?php echo $imgid; ?>" name="image_id" class="text-center center-block well well-sm">
<button type="submit" name="image" class="btn btn-success" style="margin: auto;">Update</button>
<br>
<br>
<?php } ?>
</div>
</div>
<?php
$id = $_POST['image_id'];
if (isset($_POST['image'])) {
$image = $_FILES["image"]["name"];
$image_name= addslashes($_FILES['image']['name']);
$size = $_FILES["image"] ["size"];
move_uploaded_file($_FILES["image"]["tmp_name"],"upload/" . $_FILES["image"]["name"]);
$product_img = $_FILES["image"]["name"];
mysql_query(" UPDATE fm_product_image SET img_name = '$product_img' WHERE img_id = '$id'")or die(mysql_error());
header('location:product.php');
} ?>
The problem is in your loop. You are submitting the same form, and that form contains the text fields which each image's ID. So, even if you have ten images, the IDs for all ten will be submitted, and the server will most likely use the last ID, which would be 10, and update that one.
The solution is to create a form on each iteration of your loop, that way, when you hit the submit button, it submits only the form containing the ID of a given image. Here is a solution below:
<?php $result = mysql_query("SELECT img_id, img_name FROM fm_product_image WHERE p_id_img = '$ID'")or die(mysql_error()); ?>
<?php while ($imagerows = mysql_fetch_array($result)) : ?>
<?php $imgid = $imagerows['img_id']; ?>
<img class="avatar img-circle img-thumbnail" style="border-radius: 2px; width: 70%;" src="upload/<?php echo $imagerows['img_name']; ?>">
<h6>Upload your product image.</h6>
<form method="post" action="YOUR_ACTION_PAGE" enctype="multipart/form-data">
<input type="file" name="image" class="text-center center-block well well-sm">
<input type="text" required value="<?php echo $imgid; ?>" name="image_id" class="text-center center-block well well-sm">
<button type="submit" name="image" class="btn btn-success" style="margin: auto;">Update</button>
</form>
<br>
<br>
<?php endwhile; ?>
Notice I created a new form on each iteration through the loop.
I must also mention that you need to consider switching to the better and safer mysqli_* family of functions.
The problem is that you cannot have multiple inputs of type text / file with the same name attribute in the same form tag or in the DOM in there is no form tag around the inputs.
To solve this problem, right after you open the while, add a form with a different name (e.g. name of the image that you want updated) and right before closing the while loop, close the form tag.
EDIT:
This is what I was talking about.
<?php while ($imagerows = mysql_fetch_array($result)) { $imgid = $imagerows['img_id']; ?>
<form name="update_<?php echo $imagerows['img_name']; ?>_form" method="post">
<img class="avatar img-circle img-thumbnail" style="border-radius: 2px; width: 70%;" src="upload/<?php echo $imagerows['img_name']; ?>">
<h6>Upload your product image.</h6>
<input type="file" name="image" class="text-center center-block well well-sm">
<input type="text" required value="<?php echo $imgid; ?>" name="image_id" class="text-center center-block well well-sm">
<button type="submit" name="image" class="btn btn-success" style="margin: auto;">Update</button>
<br>
<br>
</form>
<?php } ?>