Could not edit image from database PDO PHP - 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>

Related

How to remove image from folder at update phpMysql?

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

PHP - How can I show the uploaded image instantly on the same page?

Here is how the site looks like to give you an idea.
I would like to show the image he entered instantly after he clicked Bestand kiezen (= translates to chose file). How it works now is that it only shows the filename, how can I show a preview of the image instantly? The image and the other info is only inserted in the DB after clicking the add post button.
Is this supposed to be done with ajax?
The addpost.php code
<?php
include_once('classes/Post.class.php');
include_once('classes/User.class.php');
User::checklogin();
$post = Post::ShowPosts();
if(! empty($_POST)) {
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if (in_array($fileActualExt, $allowed)){
if ($fileError === 0){
if ($fileSize < 10000000){
$fileNameNew = uniqid('', true).".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
print_r($fileDestination);
move_uploaded_file($fileTmpName, $fileDestination);
$feedback = "Post has been saved.";
$title = $_POST['title'];
$desc = $_POST['description'];
$filter = $_POST['filter'];
$date = date("Y-m-d H:i:s");
$location = "";
$userid = $_SESSION['userid'];
$newPost = new Post();
$newPost->setTitle($title);
$newPost->setPicture($fileDestination);
$newPost->setDescription($desc);
$newPost->setDate($date);
$newPost->setUserId($userid);
$newPost->setLocation($location);
$newPost->setFilter($filter);
$newPost->AddPost();
$postId = Post::getLastId();
$string = $_POST['tag'];
$tags = explode(',' , $string);
foreach($tags as $t) {
$newPost->setTag($t);
$newPost->AddTags($postId);
}
} else{
$feedback = "Your file is too big.";
}
} else{
$feedback = "There was an error uploading your file.";
}
} else{
$feedback = "You cannot upload files of this type.";
}
}
?><!DOCTYPE html>
<html lang="en">
<body>
<form action="" method="post" enctype="multipart/form-data">
<h1 form__title>Add post</h1>
<?php if(isset($feedback)): ?>
<div class="feedback">
<p><?php echo $feedback; ?></p>
</div>
<?php endif; ?>
<div class="form__field">
<label for="title" class="label">YOUR SHOT TITLE:</label> <br/>
<input class="form__input" type="text" name="title">
</div>
<div class="form__field">
<label for="file" class="label">UPLOAD PICTURE</label><br/>
<input class="form__input" type="file" name="file" class="fileToUpload">
</div>
<div class="form__field">
<label for="description" class="label">DESCRIPTION</label><br/>
<textarea name="description" cols="25" rows="5"></textarea>
</div>
<div class="form__field">
<label for="tag" class="label">ADD SOME TAGS TO YOUR SHOT (seperated with , )</label><br/>
<input class="form__input" type="text" name="tag">
</div>
<p>JPG, GIF or PNG. Snapshots are 400 × 300 pixels or 800 × 600 (for HiDPI displays). </p><br/><br/>
<div class="form__field">
<label for="tag" class="label">ADD ONE (Instagram) FILTER TO YOUR SHOT </label><br/>
<select name="filter">
<option value="_1977">1977</option>
<option value="aden">aden</option>
<option value="xpro2">xpro2</option>
</select>
</div>
<div class="form__field">
<input class="btn_style" type="submit" name="submit" value="Add post"">
</div>
</form>
</body>
</html>
The Addpost function
public function AddPost(){
$conn = db::getInstance();
$query = "insert into posts (post_title, picture, description, filter, location, user_id, post_date) values (:post_title, :picture, :description, :filter, :location, :user_id, :post_date)";
$statement = $conn->prepare($query);
$statement->bindValue(':post_title',$this->getTitle());
$statement->bindValue(':picture',$this->getPicture());
$statement->bindValue(':description',$this->getDescription());
$statement->bindValue(':filter', $this->getFilter());
$statement->bindValue(':location',$this->getLocation());
$statement->bindValue(':user_id',$this->getUserId());
$statement->bindValue(':post_date',$this->getDate());
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
HTML - Display image after selecting filename
answers the question nicely with a javascript snippet look down at the first answer

PHP FileUpload is not working

I am on Ubuntu. I am trying to take user file upload of small images. I checked the $_FILES it's filled with data. I tried to debug the move command but it doesnot echo anything.
if ($_SERVER['REQUEST_METHOD'] == 'POST' ){
//Now handle everything
if(isset($_POST["submit"])) {
print_r($_FILES);
//Store the image
if(!empty($_FILES['uploaded_file']))
{
$path = "/neel/public/img/";
$path = $path.basename($_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
echo 'Its working';
} else{
echo 'I am done!!!';
die();
}
}
createnewEvent($conn);
header('Location:/neel/index.php');
}
}
You can check if the file exists by checking its name.
if(!empty($_FILES['file']['name']))
Where file is the name of input field for file.
P. G above here is correct.
Instead of checking, if $_POST['submit']
You should check this:
if(isset($_FILES['uploaded_file']['name']))
Try this code it's a complete sign up form with PHP , Bootstrap
HTML
<div class="container">
<div class="row">
<br>
<h1 class="text-center">Create new account</h1>
<br>
<div class="col-lg-4 col-md-6 col-sm-12">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<div class="form-group">
<input type="text" class="form-control form-control-lg" name="name" placeholder="Your Name">
</div>
<div class="form-group">
<input type="text" class="form-control form-control-lg" name="username" placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="password" placeholder="Password">
</div>
<div class="form-group text-center">
<div class='file-input'>
<input type='file' name="profile-img">
<span class='button label' data-js-label>Choose your profile image</span>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-success form-control form-control-lg" name="signup" value="Signup">
</div>
</form>
</div>
</div>
</div>
PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors;
if (empty($_POST['name'])) {
$errors[] = "Name field is empty";
}
if (empty($_POST['username'])) {
$errors[] = "Username field is empty";
}
if (empty($_POST['password'])) {
$errors[] = "Password field is empty";
}
if (empty($_FILES['profile-img'])) {
$errors[] = "You should upload profile image";
} else{
$img = $_FILES['profile-img'];
$ext = end(explode('.', $img['name']));
$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
$max_size = 4; //MegaBytes
if (! in_array($ext, $allowed_extensions)) {
$errors[] = "Please , Choose a valid image";
}
$img_size = $img['size'] / 1000000; // By Megabyte
if ($img_size > $max_size) {
$errors[] = "This picture is so large";
}
}
if (!empty($errors)) {
echo '<div class="container">';
foreach ($errors as $error) {
echo '
<div class="alert alert-danger" role="alert">
' . $error . '
</div>
';
}
echo "</div>";
} else {
$username = filter_var(htmlentities(trim($_POST['username'])), FILTER_SANITIZE_STRING);
$name = filter_var(htmlentities(trim($_POST['name'])), FILTER_SANITIZE_STRING);
$password = sha1(filter_var(htmlentities(trim($_POST['password'])), FILTER_SANITIZE_STRING));
// Profile Picture :-
$imgname = uniqid(uniqid()) . #date("Y-m-d") . "." . $ext;
$target_bath = "uploads/imgs/";
$target_bath = $target_bath . basename($imgname);
$orginal_img = $img['tmp_name'];
if (move_uploaded_file($orginal_img, $target_bath)) {
$sql = "INSERT INTO users(name, username, password,profile_picture, r_d) VALUES ('$name', '$username', '$password', '$target_bath', NOW())";
$result = mysqli_query($conn, $sql);
header('location: ./login.php');
}
}
}
The script you've shown shown will only "not echo anything" if $_SERVER['REQUEST_METHOD'] is not "POST". Assuming your description of events is accurate, then the problem is in the form #halojoy has asked that you show here.
I do hope that you are not redirecting the script back to itself. Also you shouldn't attempt to do a redirect after an echo.

upload image to project directory and store other data in database with Codeigniter

I’m working in form to upload image in project folder and store the other data into Database. when I try to submit this form data was submitted and image was not uploaded and one more the image was uploaded and not all of data was stored in database this is my code
model:
function update_news($data) {
extract($data);
$this->db->where('news_id', $news_id);
$this->db->update($table_name, array('title_en' => $title_en, 'title_ar' => $title_ar,'news_date' => $news_date,'image' => $image,'is_visible' => $is_visible,'main_news' => $main_news));
return true;
}
controller
public function update() {
$filename = $this->input->post('image');
$date = DateTime::createFromFormat("Y-m-d", $this->input->post('news_date'));
$data = array(
'table_name' => 'news', // pass the real table name
'news_id' => $this->input->post('news_id'),
'title_en' => $this->input->post('title_en'),
'title_ar' => $this->input->post('title_ar'),
'news_date' => $this->input->post('news_date'),
'image' => $date->format("Y") . '/' . $this->input->post('image'),
'is_visible' => $this->input->post('is_visible'),
'main_news' => $this->input->post('main_news')
);
$this->m_news_crud->update_news($data);
$folderName = 'assets/images/press-news/2015';
$config['upload_path'] = "$folderName";
if (!is_dir($folderName)) {
mkdir($folderName, 0777, TRUE);
}
$config['file_name'] = $this->input->post('image');
$config['overwrite'] = TRUE;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('userfile','image')) {
$error = array('error' => $this->upload->display_errors());
$data['error'] = $error;
$data['title_en'] = $this->input->post('title_en');
$data['title_ar'] = $this->input->post('title_ar');
$data['news_date'] = $this->input->post('news_date');
$data['image'] = base_url('assets/images/press-news/' . $date->format("Y")) . '/' . $this->input->post('image');
$data['is_visible'] = $this->input->post('is_visible');
$data['main_news'] = $this->input->post('main_news');
$data['news_id'] = $this->input->post('news_id');
$this->load->view('admin/news/d_admin_header');
$this->load->view('admin/news/vcrudedit_news', $data);
$this->load->view('admin/news/d_admin_footer');
} else {
$data = array('upload_data' => $this->upload->data());
redirect('c_news_crud/get_news_data', $data);
echo $filename;
}
}
view:
<div class="container">
<div class="col-md-9">
<?php echo form_open('C_news_crud/update', 'role="form" style="margin-top: 50px;"'); ?>
<div class="form-group">
<label for="title_en">Title Name English</label>
<input type="text" class="form-control" id="title_en" name="title_en" value="<?php echo $title_en ?>">
</div>
<div class="form-group">
<label for="title_ar">Title Name Arabic</label>
<input type="text" class="form-control" id="title_ar" name="title_ar" value="<?php echo $title_ar ?>">
</div>
<div class="form-group">
<div class="col-md-4 col-md-offset-4">
<label for="is_visible">is visible</label>
<?php
if ($is_visible == 1) {
$check_visible = 'checked="checked"';
} else {
$check_visible = ' ';
}
?>
<input role="checkbox" type="checkbox" id="is_visible" class="cbox" <?php echo $check_visible; ?> name="is_visible" value="<?php echo $is_visible; ?>">
</div>
<div class="col-md-4">
<label for="main_news">Main Arabic</label>
<?php
if ($main_news == 1) {
$check_main = 'checked="checked"';
} else {
$check_main = ' ';
}
?>
<input role="checkbox" type="checkbox" id="main_news" class="cbox" <?php echo $check_main; ?> name="main_news" value="<?php echo $main_news; ?>">
</div>
</div>
<div class="form-group">
<label for="news_date">News date</label>
<input type="date" class="form-control" id="news_date" name="news_date" value="<?php echo $news_date ?>">
</div>
<div class="form-group">
<label for="image">image</label>
<input type="file" class="form-control" id="image" name="image" value="<?php echo $image ?>">
</div>
<input type="hidden" name="news_id" value="<?php echo $news_id ?>" />
<input type="submit" name="save" class="btn btn-primary" value="Update">
<button type="button" onclick="location.href = '<?php echo site_url('C_news_crud/get_news_data') ?>'" class="btn btn-success">Back</button>
</form>
<?php echo form_close(); ?>
</div>
Make sure the path to the uploading folder is correct and it has write permission.
Make sure you are referring to the correct file input name:
$config['file_name'] = $_FILES['image']['name'];
set your uploading directory as ./assets/images/press-news/2015/
You need to display the error you get so that you know what is causing the error!
if ( ! $this->upload->do_upload()){
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
Codigniter's Upload Class

File was not uploading in codeigniter

I am uploading images in codeigniter. my file is not getting uploaded. i dont know where i am doing wrong. please find in below code
Html:
<form method="post" enctype="multipart/form-data" action="<?php echo base_url(); ?>assign_user/addStartPopup">
<div class="col-lg-6">
<div class="form-group">
<label for="image">
<input type="radio" id="image" name="start_img" onclick="rightfilefunction(1);" checked> <label for="image"> <span style="top: -2px;position: relative;">Image upload</span></label>
<label for="video" class="green">
<input type="radio" id="video" name="start_img" onclick="rightfilefunction(2);">
<span style="top: -2px;position: relative;">Video</span>
</label>
</div>
<div class="form-group" id="imageId">
<input type="file" name="imageupload" class="form-control">
</div>
<div class="form-group" id="videoId" style="display:none">
<input type="text" name="video_upload" class="form-control">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary"> Save </button>
</div>
</div>
</form>
Model:
public function startPopup(){
$createdOn = date('Y-m-d H:i:s');
if($_FILES['imageupload']['size'] != 0)
{
$files = $_FILES;
$config = array();
$config['upload_path'] = "startpage/";
$config['allowed_types'] = "png|jpg|gif";
$config['max_size'] = "5000";
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('imageupload')){
$imgdata = $this->upload->data();
$image_config=array();
$image_config["image_library"] = "gd2";
$image_config['overwrite'] = TRUE;
$image_config["source_image"] = $imgdata["full_path"];
$image_config['create_thumb'] = FALSE;
$image_config['maintain_ratio'] = TRUE;
$image_config['new_image'] = $imgdata["file_path"].$imgdata["file_name"];
$image_config['quality'] = "95%";
$image_config['width'] = 170;
$image_config['height'] = 170;
$this->load->library('image_lib',$image_config);
$this->image_lib->initialize($image_config);
$this->image_lib->resize();
$logo = 'startpage/'.$imgdata["file_name"];
$query = $this->db->query("INSERT INTO `startpop` (content_view, created_on) VALUES ('$logo', '$createdOn')");
if($query){
return 1;
}
}else
{
echo "not uploaded";
}
}else{
$prv = $this->input->post('video_upload');
$query = $this->db->query("INSERT INTO `startpop` (content_view, created_on) VALUES ('$prv', '$createdOn')");
if($query){
return 1;
}
}
}
Controller:
public function addStartPopup(){
$result = $this->model->startPopup();
if($result > 0){
$data['mgs'] = "Added Successfully ..!";
$this->load->view('admin/startPage',$data);
}
}
From this above code, i am getting the error "not uploaded". can any one tell me where i am doing wrong

Categories