How to remove image from folder at update phpMysql? - php

Update query from the database:
<?php
include 'dpconnection.php';
$uid=$_REQUEST['upid'];
if (isset($_POST['update'])) {
$category= $_POST['category'];
$pname= $_POST['pname'];
$parea= $_POST['parea'];
$pPrices= $_POST['pPrices'];
$pAddress= $_POST['pAddress'];
$filename = $_FILES['new_image']['name'] ;
$tempname = $_FILES['new_image']['tmp_name'] ;
$filesize = $_FILES['new_image']['size'] ;
$fileextension = explode('.', $filename) ;
$fileextension = strtolower(end($fileextension));
$newfilename = uniqid().'images'.'.'.$fileextension ;
$path = "media/".$newfilename ;
$sql = mysqli_query($conn,"UPDATE product SET c_id='$category', p_name='$pname', p_area='$parea', p_prices='$pPrices',p_address='$pAddress', p_thumb_image='$path' WHERE p_id='$uid'");
if (move_uploaded_file($tempname, $path) && $sql) {
echo "<script>alert('Record Updated successfully');</script>";
echo "<script>location.href = 'adminViewProduct.php';</script>";
} else {
echo "Error updating record: " . $conn->error;
}
}
?>
Image not deleting from folder, i have two if statement but just one else statement so it looks like i am missing something but i really don't know what i am missing.
This is form:
<div class="form-group">
<label>Address</label>
<input class="form-control" type="text" name="pAddress" value="<?php echo $row1['p_address'];?>">
</div>
<div class="form-group">
<label>Thumb Image</label>
<input type="file" name="new_image" class="form-control">
<input class="form-control" type="hidden" name="pimage" value="<?php echo $row1['p_thumb_image'];?>">
<img class="float-left" src="<?php echo $row1['p_thumb_image'];?>" width="100px;"><br><br>
</div>
<div class="form-group text-center">
<input class="btn btn-primary" type="submit" name="update" value="Update">
</div>
</form>

You don't have a code that delete the files in php there's a function called unlink where you can delete a files but first you need fetch the path or filename and delete it before updating your data.
Here is the link of unlink.
https://www.php.net/manual/en/function.unlink.php

Related

Could not edit image from database PDO PHP

I can succesfully save the image from my database using this code
if(isset($_POST['btn-update'])){
$id = $_REQUEST['id'];
$sql = "SELECT * FROM article WHERE id=:id";
$query= $db_con->prepare($sql);
$query->execute(array(':id' => $id));
while($row=$query->fetch(PDO::FETCH_ASSOC)){
$images_ = $row['image'];
$files_ = $row['file'];
}
$file_image = $_FILES['image-files'];
$file_image_Name = $_FILES['image-files']['name'];
$file_image_TmpName = $_FILES['image-files']['tmp_name'];
$file_image_Size = $_FILES['image-files']['size'];
$file_image_Error = $_FILES['image-files']['error'];
$file_image_Type = $_FILES['image-files']['type'];
if(!empty($_FILES['image-files']['tmp_name'])){
//handle first upload
$file_image_Ext = explode('.', $file_image_Name);
$file_image_ActualExt = strtolower(end($file_image_Ext));
$file_image_allowed = array("jpg", "jpeg", "png");
if(in_array($file_image_ActualExt, $file_image_allowed)){
if($file_image_Error === 0){
if($file_image_Size < 1000000){
$file_image_NameNew = "image-".uniqid('',true).'.'.$file_image_ActualExt;
$file_image_Destination = 'uploaded_files/uploaded_files_articles_images/' .$file_image_NameNew;
move_uploaded_file($file_image_TmpName, $file_image_Destination);
}else{
echo "You file size is too big!";
}
}else{
echo "There was an error uploading the file!";
}
}else{
echo "You cannot upload files of this type!";
}
}else{
$file_image_NameNew = '';
}
if($user->InsertArticle($articleTitle,$date_today,$bodyContent,$file_image_NameNew))
{
header("Location:admin-index?UploadedSuccesfully!");
}
}
Now what I am trying to do is edit the image but it seems like my code is missing something and I couldn't figure out why is it not succesfully editing.
Here's my code for editing the image from database
$location = $_FILES['image']['name'];
$fileTmpNameLocation = $_FILES['image']['tmp_name'];
if(!empty($_FILES['image']['tmp_name'])){
//allow file types
$fileExtLocation = explode('.', $location);
$fileActualExtLocation = strtolower(end($fileExtLocation));
$allowedLocation = array("jpg", "jpeg", "png");
if(in_array($fileActualExtLocation, $allowedLocation)){
$fileNameNewLocation = $images_;
$fileDestinationLocation = 'uploaded_files/uploaded_files_articles_images/' .$fileNameNewLocation;
move_uploaded_file($fileTmpNameLocation, $fileDestinationLocation);
}
}else{
$fileNameNewLocation = '';
}
if($user->UpdateFile($id,$title,$content,$fileNameNewLocation)){
$user->Redirect('edit-index.php?UpdatedSuccesfully');
}else{
echo "There's something wrong!";
}
Here's my UpdateFile Method
public function UpdateFile($id,$title, $content, $image){
try{
$stmt = $this->db->prepare("UPDATE article SET title=:title, content=:content, image=:image WHERE id=:id");
$stmt->bindParam(":title", $title);
$stmt->bindParam(":content", $content);
$stmt->bindParam(":image", $image);
$stmt->bindParam(":id", $id);
$stmt->execute();
return $stmt;
}catch(PDOException $ex){
echo $ex->getMessage();
}
}
Could someone help me out please.
EDIT:
<form action = "edit.php" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Title of the Article</label>
<input type="text" class="form-control" id="title" name="title" value="<?php echo $title; ?>">
<br \>
<label for="bodyContent">Content</label>
<textarea class="form-control" rows="5" id="content" name="content"><?php echo $content; ?></textarea>
<br>
<div class="row">
<div class="col-md-4">
<label for="exampleFormControlFile1">Upload Image Only</label>
<input type="file" name="image" class="form-control-file" id="image">
<div class="col-md-12">
<?php
if(empty($images_)){
//nnothing to display
}else{
echo "<img src='uploaded_files/uploaded_files_articles_images/$images_' class='img-responsive img-rounded'>";
}
?>
</div>
</div>
<div class="col-md-4">
<label for="exampleFormControlFile1">Upload File</label>
<input type="file" name="files" class="form-control-file" id="files">
<div class="col-md-12">
<?php
if(empty($files_)){
//nothing to display
}else{
echo "<a href='uploaded_files/uploaded_files_articles/$files_' download>".$files_."</p>";
}
?>
</div>
</div>
<div class="col-md-4">
<input type="hidden" name="id" value=<?php echo $_GET['id']; ?>>
</div>
</div>
<br>
<button type="submit" name="btn-update" class="btn btn-primary">Update</button>
</div>
</form>

Upload in files in for loop

I am using this upload script http://www.dropzonejs.com
The upload php part is:
foreach($_POST["id"] as $key=>$value)
{
$id = trim(mysqli_real_escape_string($mysqli, $value));
$pre_set = trim(mysqli_real_escape_string($mysqli, $_POST['pre_set'][$key]));
$keep_filename = trim(mysqli_real_escape_string($mysqli, $_POST['keep_filename'][$key]));
$ds = DIRECTORY_SEPARATOR;
$storeFolder = '../uploads';
if (!empty($_FILES))
{
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
if($keep_filename == 'yes')
{
$targetFile = $targetPath. $pre_set.'_'.$id.'_'.$_FILES['file']['name'];
}
else
{
$targetFile = $targetPath. $pre_set.'_'.$id.'.'.pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
}
move_uploaded_file($tempFile,$targetFile);
}
}
When using this with an standard form as shown below the file is correctly uploaded and renamed:
<form action="includes/upload.php" class="dropzone">
<input type="hidden" class="form-control" id="id[]" name="id[]" value="'.$row['id'].'">
<input type="hidden" class="form-control" id="pre_set[]" name="pre_set[]" value="logo">
<input type="hidden" class="form-control" id="keep_filename[]" name="keep_filename[]" value="no">
</form>
But when using a for loop situation an image is shown in the upload window but the file is not uploaded.
I am not getting any errors (or not using the correct parameter to see it)
while($row = mysqli_fetch_array($res))
{ $i++;
echo'
<div class="container">
<form action="includes/upload.php">
<div class="form-group col-md-3">';
if($i == 1) { echo '<label>Voeg foto toe</label>'; } echo'
<div class="dropzone dropzone_small" id="myId'.$i.'">
<div class="fallback">
<input type="hidden" class="form-control" id="id[]" name="id[]" value="xxxx">
<input type="hidden" class="form-control" id="pre_set[]" name="pre_set[]" value="toolbox_">
<input type="hidden" class="form-control" id="keep_filename[]" name="keep_filename[]" value="yes">
</div>
</div>
</div>
</form>';
}
Any suggestions to change the code to get this working?
Help is much appreciated.
You must start your form with
<form action="includes/upload.php"> method="post" enctype="multipart/form-data">
// your form attributes here
</form>

Upload multiple images in php

i am creating a page called events i have created a form which submits on post file, this is my form code, `
Adding Staff
<div class="box">
<label>Heading</label>
<input type="text" name="heading" id="heading"/>
</div>
<div class="box" style="margin-left: 120px">
<label>Description 1</label>
<textarea cols="30" rows="5" name="description_1" id="description_1"></textarea>
</div>
<div class="box">
<label>Description 2</label>
<textarea cols="30" rows="5" name="description_2" id="description_2"></textarea>
</div>
<div class="clear"> </div>
<div class="box">
<label>Upload Images</label>
<input type="file" name="picture" id="picture"/>
<label>Is Rename <input type="checkbox" name="is_rename"> </label>
</div>
<div class="clear"> </div>
<div class="box" style="width: 100px; margin-left: 350px;">
<input style="padding: 4px" type="submit" name="submit" value="submit">
</div>`
This is my post
<?php
ob_start();
session_start();
include_once "../../classes/addClasses.php";
$heading = $_POST['heading'];
$description_1 = $_POST['description_1'];
$description_2 = $_POST['description_2'];
$picture = $_POST['picture'];
$target_dir = "../../../uploads/";
$target_file = $target_dir . basename($_FILES["picture"]["name"]);
print_r($_FILES);
if( isset( $_POST['is_rename'] ) )
$file_name = time().'-'.basename($_FILES["picture"]["name"]);
else
$file_name = basename($_FILES["picture"]["name"]);
if(empty($_FILES['picture']['name'])){
echo "please select a file to upload";
?>
<script>window.location.href="http://localhost/learner-pack/admin/admin/add_events.php?error=empty"</script>
<?php
}
$target_file = $target_dir . $file_name;
if (move_uploaded_file($_FILES["picture"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["picture"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
if (file_exists($target_file)) {
echo "Sorry, file '".$file_name."' already exists.";
}elseif (move_uploaded_file($_FILES["picture"]["tmp_name"], $target_file)) {
echo "The file " . $file_name . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
/*$created_by = $_POST['created_by'];
$updated_by = $_POST['updated_by'];
$current_date = $_POST['current_date'];
$updated_date = $_POST['updated_date'];
$visitor_counter = $_POST['visitor_counter'];*/
if($admin->addingEvents($heading,$description_1,$description_2, $file_name))
{
header('Location: ../view_events.php?added=true');
}
else
{
echo "Error";
}
?>
please help me to store multiple images in table using one field and retireve them to view on events page when i fetch one row so that all images on that row are fetchable

PHP image Doesn't show,

The image is stored on the database and everytime when I upload an image on the web page, the database does work and update the database profile section but it is not showing on the web browser. :/ i tried different browsers but every browser failed to display the image, the Alt parameter of image does show but no image, i have inspected the page element the image path is there but i can't see the image there?
the code in the profile page is:
<?php
function change_profile_image($userID, $file_temp, $file_extn) {
$file_path ='C:/xampp/htdocs/cricket/user/images/profile/'. substr(md5(time()), 0, 10) . '.' . $file_extn;
move_uploaded_file($file_temp, $file_path);
mysql_query("UPDATE `user` SET `profile` = '" . mysql_real_escape_string($file_path) . "' WHERE `userID` = " . (int)$userID);
}
?>
<?php
$query = "select * from user where userID='".$_SESSION['id']."'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result)
?>
<link rel="stylesheet" type="text/css" href="../css/style.css">
<div id="content">
<h1>Edit Your Information</h1>
<div class="profile">
<?php
if (isset($_FILES['profile'])=== true) {
if (empty($_FILES['profile']['name']) === true) {
echo "Please choose a file!";
} else {
$allowed = array('jpg', 'jpeg', 'gif', 'png');
$file_name = $_FILES['profile']['name'];
$file_extn = strtolower(end(explode('.', $file_name)));
$file_temp = $_FILES['profile']['tmp_name'];
if (in_array($file_extn, $allowed)=== true) {
change_profile_image($_SESSION['id'], $file_temp, $file_extn);
} else {
echo "incorrect file type, Allowed: ";
echo implode(', ', $allowed);
}
}
}
if (empty($row['profile']) === false) {
echo '<img src="', $row['profile'], '" alt="', $row['user_firstname'], '\'s Profile Image">';
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="profile"> <br> <input type="submit">
</form>
</div>
<form method="post" action="">
<div class="txtbox1">Email</div>
<div class="txtbox">
<input type="text" name="email" value="<?php echo $row['user_email']?>"> </div><br><br><br>
<div class="txtbox1">First Name</div>
<div class="txtbox">
<input type="text" name="firstname" value="<?php echo $row['user_firstname']?>"></div><br><br><br>
<div class="txtbox1">Surname</div>
<div class="txtbox">
<input type="text" name="lastname" value="<?php echo $row['user_surname']?>"></div><br><br><br>
<div class="txtbox1">DOB</div>
<div class="txtbox">
<input type="text" name="dob" value="<?php echo $row['user_dob']?>"></div><br>
<div class="txtbox"><input type="submit" value="update" name="update"> </div>
</form>
<?php
if(isset($_POST['update'])){
$query1 = "update user set user_email='".$_POST['email']."', user_firstname='".$_POST['firstname']."', user_surname='".$_POST['lastname']."', user_dob='".$_POST['dob']."' where userID='".$_SESSION['id']."'";
$result1 = mysql_query($query1);
echo "<script>alert('Your Information has been changed SuccessFully..'); window.location = './edit.php';</script>";
}
?>
</div>
If anyone is interested in the CSS the styling code is:
.profile {
background:white;
border:1px dashed #ccc;
padding:5px;
}
.profile img {
width=100%;
}
i will really appreciate if anyone can guide me or help me in the right direction

How to add multiple images using browse button

I have a following code where I can upload a single image. This image gets stored in both database and folder. Now what I want is to add multiple images. How can I do that. Help me to come out of this.
<?php
$uploadDir ="C:/wamp/www/dragongym/customers/";
if(isset($_POST['submit']))
{
$intime =DATE("H:i", STRTOTIME($_POST['intime']));
$outtime =DATE("H:i", STRTOTIME($_POST['outtime']));
date_default_timezone_set('Asia/Calcutta');
$today = date("Y-m-d");
$msg="";
$res = "SELECT customer_id FROM customer ORDER by customer_id DESC LIMIT 1";
$qur = mysql_query($res);
while($row = mysql_fetch_array($qur, MYSQL_BOTH))
{
$last_id = $row['customer_id'];
$plus_id = 1;
}
if( $last_id !="")
{
$cust_id = $last_id + $plus_id;
}
$filePath="";
if($_FILES['cimage']['size'] > 0)
{
// echo $cust_id;
// Temporary file name stored on the server for pdf
$filename = basename($_FILES['cimage']['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = $cust_id.'.'.$extension;
$tmpName1 = $_FILES['cimage']['tmp_name'];
$fileSize = $_FILES['cimage']['size'];
$fileType = $_FILES['cimage']['type'];
$filePath = $uploadDir . $new;
$resultes = move_uploaded_file($tmpName1, $filePath);
if (!$resultes)
{
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$new = addslashes($new);
$filePath = addslashes($filePath);
}
}
$sql = 'INSERT INTO customer(customer_name,roll_no,customer_number,customer_address,tariff_id,intime,outtime,customer_image,active,joining_date) VALUES("'.$_POST['name'].'","'.$_POST['roll'].'","'.$_POST['number'].'","'.$_POST['address'].'","'.$_POST['tariff'].'","'.$intime.'","'.$outtime.'","'.$filePath.'","1","'.$today.'")';
$msg="<p style=\"color:#99CC00; font-size:13px;\"> Successfully!</p>";
if (!mysql_query($sql, $link))
{
die('Error: ' . mysql_error());
}
}
?>
<form action="#" method="post" enctype="multipart/form-data">
<h2>Registration Form</h2><?php echo $msg; ?>
<label>Name</label>
<input type="text" value="" name="name" id="name" required class="txtfield">
<label>Roll Number</label>
<input type="text" value="" name="roll" id="roll" required class="txtfield">
<label>Mobile Number</label>
<input type="text" value="" name="number" required class="txtfield" id="mobnum">
<label>Address</label>
<textarea name="address" class="txtfield"></textarea>
<label>Upload Photo</label>
<input type="file" value="" name="cimage" class="txtfield">
<!-- <label style="display: block">Timing</label>
<input type="text" value="" name="intime" placeholder="Intime" required class="timefield timepicker">
<input type="text" value="" name="outtime" placeholder="Outtime" required class="timefield timepicker">-->
<input type="submit" value="Save" name="submit" class="btn buttonside1">
</form>
You can use jquery plugin for that..
there is lots of plugin available on google..try this one http://blueimp.github.io/jQuery-File-Upload/
to do multiple file upload you should first have multiple="true" in your tab like so
<input type="file" name='files[]' multiple='true'/>
then use foreach loop to upload files.

Categories