While updating the record if I do not upload the image and click on update button the current image will be removed.
Here is the code
<?php
if (isset($_POST['update_record'])){
$edit_id = $_GET['edit'];
$username = $_POST['name'];
$email = $_POST['email'];
$city = $_POST['city'];
$file_name = $_FILES['file']['name'];
$file_tmp_name = $_FILES['file']['tmp_name'];
$file_error = $_FILES['file']['error'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$allowed = ['png' , 'jpg' , 'jpeg'];
$pathinfo = pathinfo($file_name , PATHINFO_EXTENSION);
$destination = "uploads/" . $file_name ;
if (in_array($pathinfo , $allowed)){
if ($file_size < 100000){
if ($file_error === 0){
move_uploaded_file($file_tmp_name, $destination) ;
} //error close here
else{
echo "Some kind of error";
}
} //size close here
else{
echo "File Size is too big!";
}
} //type close here
else{
echo "File type is wronng";
}
$update_query = "UPDATE crud
SET `name`='$username' , `email`='$email' ,
`city`='$city', `image`='$destination'
WHERE id=$edit_id";
$run = mysqli_query($connect, $update_query) ;
if ($run){
header("Location: show_record.php") ;
} else{
echo "Error in Updating the data";
}
} //main if isset close here
?>
verify that a file exists before proceeding. if no file exist, then DO NOT update the $destination in your update query
//use a flag
$fileExists = false;
if(!empty($_FILES['file'])) { //check here
$fileExists = true;
//rest of the file upload code
}
if($fileExists === true){
// a file was uploaded. now update $destination variable in update query as well
}
Related
Image Upload working fine in localhost but it is not working in live server.HTML form shows success message after submitting the form but no data is stored in the database.I have tried to print error but there is no error. My Code :
<?php
include './login_validity.php';
$res = '';
$mes = '';
$img = NULL;
if (isset($_POST['submit'])) {
$name = $_POST['title'];
$des = $_POST['description'];
$shrt_detail = $_POST['shrt_description'];
$date = $_POST['date'];
$show_status = $_POST['is_show'];
$detail = $des;
//------------------image upload---------------------
if (!empty($_FILES["fileToUpload"]["name"])) {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if ($check !== false) {
$uploadOk = 1;
} else {
$_SESSION['message'] = "File is not an image.";
$uploadOk = 0;
}
// Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" && $imageFileType != "tif")
{
$_SESSION['message'] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$_SESSION['message'] = "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$_SESSION['message'] = "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
} else {
$_SESSION['message'] = "Sorry, there was an error uploading your file.";
}
}
$img = $target_file;
}
$query = "INSERT INTO slider (title,image,shrt_description,description,date,is_show) VALUES ('$name','$img','$shrt_detail','$detail','$date','$show_status')";
$res = $conn->query($query);
$mes = "Successfully Added";
}
?>
After submitting the form I have checked the uploads folder in server.I found the uploaded file on that folder. But when I checked phpMyadmin no data in database about that uploaded file. But when I run this page in localhost then everything is working fine.
I think that your problem is here:
$res = '';
$mes = '';
$img = NULL;
if (isset($_POST['submit'])) {
$name = $_POST['title'];
$des = $_POST['description'];
$shrt_detail = $_POST['shrt_description'];
$date = $_POST['date'];
$show_status = $_POST['is_show'];
$detail = $des;
You have to change it to:
$res = '';
$mes = '';
if (isset($_POST['submit'])) {
$name = $_POST['title'];
$des = $_POST['description'];
$shrt_detail = $_POST['shrt_description'];
$date = $_POST['date'];
$show_status = $_POST['is_show'];
$detail = $des;
$img = $_FILES['fileToUpload']['name'];
If you do $img = NULL; your not receiving it.
You have to do $img = $_FILES['fileToUpload']['name']; in order to get the submitted data from the form
P.S - Where are you declaring the variable $conn? I think you have to include your connection in that document, otherwise it won't send the data to your database.
I am new to PHP, I am trying to upload text files to my database. The part, where I am adding the uploaded file to a specified folder works, but I can't add anything to the database. I've found out that the reason for it is that my_sqli_query returns false, but I have no idea, as what is the reason for it. Thanks for help!
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "project";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
if(isset($_POST['submit'])) {
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$book_title = mysqli_real_escape_string($conn, $_POST['book_title']);
$book_author = mysqli_real_escape_string($conn, $_POST['book_author']);
$book_publisher = mysqli_real_escape_string($conn, $_POST['book_publisher']);
$book_year = mysqli_real_escape_string($conn, $_POST['book_year']);
$book_genre = mysqli_real_escape_string($conn, $_POST['book_genre']);
$fileExt = explode('.', $fileName);
$fileAExt = strtolower(end($fileExt));
$allowedExtensions = array('epub', 'mobi', 'pdf', 'txt');
if (empty($book_title) || empty($book_author) || empty($book_publisher) || empty($book_year) || empty($book_genre)) {
header("Location: ../upload.php?empty");
exit();
}else{
if (in_array($fileAExt, $allowedExtensions)) {
if ($fileError === 0) {
if ($fileSize < 100000) {
$fileNewFilename = uniqid('', true) . $fileName . "." . $fileAExt;
$fileDest = 'uploads/' . $fileNewFilename;
$sql = "INSERT INTO book_db (book_title, book_author, book_publisher, book_year, book_year, file) VALUES ('$book_title', '$book_author', '$book_publisher', '$book_year', '$book_genre', '$file');";
$query = mysqli_query($conn, $sql);
var_dump($query);
move_uploaded_file($fileTmpName, $fileDest);
if ($query != null) {
header("Location: index.php?fail");
} else {
header("Location: index.php?fail");
}
} else {
echo 'fail, too large';
}
} else {
echo 'fail, error';
}
} else {
echo 'fail';
}
}
}
<?php
include("config.php");
//Get the name of the input type submit
if(ISSET($_POST['sign_up'])) {
$username = trim($_POST['user']);
$password = trim($_POST['pass']);
$gender=$_POST['gen'];
$firstname =($_POST['first']);
$lastname = trim($_POST['last']);
$y=$_POST['y'];
$m=$_POST['m'];
$d=$_POST['d'];
$dob=$y."-".$m."-".$d;
$imgpath=$_FILES['file']['name'];
$imgFile = $_FILES['file']['name'];
$tmp_dir = $_FILES['file']['tmp_name'];
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION));
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif');
$userpic = rand(1000,1000000).".".$imgExt;
if(!empty($username) && !empty($password)) {
$sql = mysql_query("SELECT * FROM users WHERE user_name = '$username'") or die(mysql_error());
if(mysql_num_rows($sql) > 0) {
$msg_error = "Username already registered!";
} else {
if(in_array($imgExt, $valid_extensions)){
mysql_query("INSERT INTO users
values('','$username','".MD5($password)."', '$gender',
'$dob', '$imgpath', 'guest',
'$firstname', '$lastname')")
or die(mysql_error());
$uuid=mysql_query("SELECT * FROM users");
while ($puid=mysql_fetch_array($uuid)){
$pid = $puid['user_id'];
mkdir("userImages/$pid");
move_uploaded_file($_FILES["file"]["tmp_name"], "userImages/$pid/" . $_FILES["file"]["name"]);
}
//image uploaded should be moved to my specified
//folder after the code above is executed
$_SESSION['sname']=$_POST['user'];
$msg_success = "You are now registered!";
}
else{
$msg_error = "Invalid image!";
}
}
}else{
$msg_error = "All fields are required!";
}
}
?>
this is my php code. Can someone help me in figuring out why my 'move_uploaded_file()' is not working?
Check your destination folder permissions. error_get_last could give you some clue to why it doesn't work. Check this example
$targetFile = "userImages/$pid/" . $_FILES["file"]["name"];
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
echo "<P>FILE UPLOADED TO: $target_file</P>";
} else {
echo "<P>MOVE UPLOADED FILE FAILED!</P>";
print_r(error_get_last());
}
i am trying to update name ,email , image informations in form.
name, email was updating fine, but image was not saving in folder, so i removed ; in below line :
if ($user_home->update($uname,$email, $phone, $uid)); ,
now once we click on "save" button, images are saving in folders,
but name & emails are displaying old values, & after refreshing page displaying updated values. but i want to display updated values once we click on save button.
form
<form action="profile.php" method="POST" enctype="multipart/form-data">
Name :
<?php echo $row['userName'] ?> <br/>
Email :
<?php echo $row['userEmail'] ?> <br>
<h3>photo</h3>
<input type="file" name="photo" id="fileSelect"><br>
<input type="submit" name="submit" value="Save" />
</form>
code for name ,email
<?php
include 'home.php';
// session_start();
require_once 'class.user.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
header("Location: index.php");
die();
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<?php
$FORM['uname'] = "";
$FORM['txtuname'] = "";
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$phone = $_POST['phone'];
$uid = (isset($_GET['userID']) ? intval($_GET['userID']) : -1);
// query
if ($user_home->update($uname,$email, $phone, $uid)); // This is the line
{
header("Location: profile.php");
die();
}
}
?>
code for image
<?php
if(isset($_FILES["photo"]["error"])){
if($_FILES["photo"]["error"] > 0){
echo "Error: " . $_FILES["photo"]["error"] . "<br>";
} else{
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $_FILES["photo"]["name"])){
echo $_FILES["photo"]["name"] . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: There was a problem uploading your file - please try again.";
}
}
} else{
echo "Error: Invalid parameters - please contact your server administrator.";
}
?>
You need to do the select query after the update query, otherwise you are getting the old info and then update the record in the database.
<?php
include 'home.php';
// session_start();
require_once 'class.user.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
header("Location: index.php");
die();
}
$FORM['uname'] = "";
$FORM['txtuname'] = "";
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$phone = $_POST['phone'];
$uid = (isset($_SESSION['userSession']) ? intval($_SESSION['userSession']) : 0);
// query
if ($uid > 0 && $user_home->update($uname,$email, $phone, $uid)) // This is the line
{
header("Location: profile.php");
die();
}
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
Or you can use this custom update:
// query
if ($uid > 0)
{
$stmt = $user_home->runQuery("UPDATE tbl_users SET userName=:uname,
userEmail=:email, phone=:phone WHERE userID=:uid");
$stmt->execute(array(
":uid"=>$_SESSION['userSession'],
":email" => $email,
":phone" => $phone,
":uname" => $uname
));
header("Location: profile.php");
die();
}
So, i've been wondering for this script and still can't get it right. For some reason it won't save to my database. Any ideas why it's not working? Would appreciate any help. Thanks! Here's my script.
<?php
include_once ("database.php"); ?>
<?php
if (isset($_POST['anisave'])) {
$id = $_POST['id'];
$title = $_POST['title'];
$genre = $_POST['genre'];
$description = $_POST['description'];
$start = $_POST['start'];
$stop = $_POST['stop'];
$image_file = $_FILES['image']['name'];
$type = $_FILES['image']['type'];
$size = $_FILES['image']['size'];
if (empty($image_file) || empty($id)) {
echo "Sorry, form is not complete yet!";
header('Location: add.php');
}
else{
$query_id = mysql_query("SELECT * FROM anidata WHERE id = '$id'");
$check = mysql_num_rows($query_id);
if ($check > 0) {
echo "Sorry, Anime ID not available";
header('Location: add.php');
}
else{
if ($type != "image/gif" && $type != "image/jpg" && $type != "image/jpeg" && $type != "image/png") {
echo "Invalid image file, please use JPEG,JPG,PNG or GIF to upload the image."
header('Location: add.php');
}
if ($size > 10000) {
echo "Affordable file is under 10mB."
header('Location: add.php');
}
else{
$upload_directory = 'upload/';
$temp = $upload_directory.$image_file;
if (move_uploaded_file($_FILES['image']['tmp_name'] , $temp)) {
$sql = "INSERT INTO anidata VALUES ('$id', '$title', '$temp', '$genre', '$description','$start', '$stop')";
$query = mysql_query($sql)
if ($query) {
header('Location: view.php');
}
else{
echo mysql_query();
}
}
else{
echo "<p> Upload Failed, error code = " . $_FILES['location']['error']. "</p>";
}
}
}
}
}
else{
unset($_POST['anisave']);
}
?>