why the picture gone after do the update data in PHP - php

lets say i have 2 column in my inventory data called category and image_name in my php and database.
image_name are coming from this (basically in my database, image_name contain the link of the uploaded image) :
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$file = $_FILES['uploadgambar'];
$fileName = $_FILES['uploadgambar']['name'];
$fileTmpName = $_FILES['uploadgambar']['tmp_name'];
$fileSize = $_FILES['uploadgambar']['size'];
$fileError = $_FILES['uploadgambar']['error'];
$fileType = $_FILES['uploadgambar']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 5000000) {
$fileNameNew = uniqid('', true) . "." . $fileActualExt;
$fileDestination = 'uploads/' . $fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
// header("Location: index.php?uploadsuccess");
} else {
echo "File anda terlalu besar (maximal 1gb)";
}
} else {
echo "Terdapat error dalam mengupload file";
}
} else {
echo "Anda tidak bisa upload file ini karena tidak berbentuk JPG/JPEG/PNG";
}
i build some code for update feature for category and image_name column like this
$kategori = mysqli_real_escape_string($conn, $_POST["kategori"]);
$image_name = mysqli_real_escape_string($conn, $fileDestination);
and here's for the update
$sql1 = "update $tabeldatabase set kategori='$kategori', image_name = '$image_name' where kode = '$kode';
$updatean = mysqli_query($conn, $sql1);
echo "<script type='text/javascript'> alert('Berhasil, Data barang telah diupdate!'); </script>";
echo "<script type='text/javascript'>window.location = '$forwardpage';</script>";
but the problem is, when i update the image its run, but when i update kategori, idk why my picture gone and when i look at the database, column image_name has removed for that id and cause the image gone.
my expected result is, just like update feature, if i update the category, then the image_name wont missing.

I am writing your answer, but maybe it needs some editions. so add some comments if the ways not fix the problem.
one of the reasons maybe due to updating the row of database even if the file name is empty. so you must check the file name before update the database table record.
In this code, whenever you don't have upload file, so $fileDestination will be empty, so the cell of table will be empty and image address will gone!
For that problem, you could change the query:
$sql1 = "update $tabeldatabase set kategori='$kategori', image_name = '$image_name' where kode = '$kode';
to something like this:
if ($image_name) {
$sql1 = "update $tabeldatabase set kategori='$kategori', image_name = '$image_name' where kode = '$kode';
} else {
$sql1 = "update $tabeldatabase set kategori='$kategori' where kode = '$kode';
}
Apart from this I recommend you to change this row:
$sql1 = "update $tabeldatabase set kategori='$kategori', image_name = '$image_name' where kode = '$kode';
to a fixed table name like this:
$sql1 = "update my_static_table_name set kategori='$kategori', image_name = '$image_name' where kode = '$kode';
so you can easily debug the problem.

Related

How to add profile image to user php

I want a logged in user to add a profile picture. No errors are shown, the picture is just not added to the folder where it should be.
I know I have to use prepared statements, I will. I just want to sort this problem out first.
When the user has not changed the profile pic, the default picture displays perfectly. The file profile pic just wont upload to the folder.
This is the page where you change the picture.
<?php
session_start();
include_once 'dbh.php';
<html>
<body>
<?php
$sql = "SELECT * FROM user";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$sqlImg = "SELECT * FROM profileimg WHERE userid='$id'";
$resultImg = mysqli_query($conn, $sqlImg);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
echo "<div>";
if ($rowImg['status'] == 0) {
echo "<img src='uploads/profile".$id.".jpg'>";
}
else {
echo "<img src='uploads/male.jpg'>";
}
echo "<p>".$row['username']."</p>";
echo "</div>";
}
}
}
else {
echo "There are no users!";
}
if (isset($_SESSION['id'])) {
echo "You are logged in!";
echo '<form action="includes/upload.inc.php" method="post"
enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit" name="submit">UPLOAD FILE</button>
</form>';
}
else {
echo "You are not logged in!";
}
?>
This is the php page for the upload
<?php
session_start();
include_once 'dbh.php';
$id = $_SESSION['id'];
if (isset($_POST['submit'])) {
$file = $_FILES['file'];
$fileName = $file['name'];
$fileType = $file['type'];
$fileTempName = $file['tmp_name'];
$fileError = $file['error'];
$fileSize = $file['size'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg", "jpeg", "png", "pdf");
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 500000) {
//I now need to create a unique ID which we use to replace the name
of the uploaded file, before inserting it into our rootfolder
//If I don't do this, we might end up overwriting the file if we
upload a file later with the same name
//Here I use the user ID of the user to create the first part of the
image name
$fileNameNew = "profile".$id.".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE profileimg SET status=0 WHERE userid='$id';";
$result = mysqli_query($conn, $sql);
header("Location: index.php?uploadsuccess");
}
else {
echo "Your file is too big!";
}
}
else {
echo "There was an error uploading your file, try again!";
}
}
else {
echo "You cannot upload files of this type!";
}
}
First, ensure that PHP is configured to allow file uploads.
In your "php.ini" file, search for the file_uploads directive, and set it to On:
I suspect logical issue near your below update query:
$sql = "UPDATE profileimg SET status=0 WHERE userid='$id';";
Your logic will run fine for only those users who already having corresponding record in profileimg table. But UPDATE query will do nothing for new user.
So, you will have to first check whether there is a record in profileimg for particular user. If no record then run INSERT query, if record exists then run UPDATE query..

cant see image from avatar_path

i am storing image in uploads folder an then in a random directory but it is not being shown in my website this is my code
<?php
$query = "SELECT * FROM users WHERE email='$email' or username = '$email'or mobile='$email'";
$fire = mysqli_query($con,$query) or die("can not fetch data from database ".mysqli_error($con));
if (mysqli_num_rows($fire)>0) {
$users = mysqli_fetch_assoc($fire);
}
?>
<img src="<?php echo $users['avatar_path']?>" width='100' height='100' class='avatar'>
and this is my upload code
if (isset($_POST['uploadimg'])) {
$avatar = $_FILES['avatar'];
$avatar_name = $_FILES['avatar']['name'];
$avatar_tmpname = $_FILES['avatar']['tmp_name'];
$avatar_size = $_FILES['avatar']['size'];
$avatar_type = $_FILES['avatar']['type'];
$avatar_ext = pathinfo($avatar_name, PATHINFO_EXTENSION);
if (!empty($avatar_name)) {
if ($avatar_size <= 25000000) {
if ($avatar_ext == "jpg" || $avatar_ext == "jpeg" ||$avatar_ext == "png" ) {
$chars= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$rand_dir_name=substr(str_shuffle($chars),0,15);
mkdir("uploads/$rand_dir_name");
$final_file= "uploads/$rand_dir_name/$avatar_name";
$upload = move_uploaded_file($avatar_tmpname, $final_file);
if ($upload) {
unlink("$avatar_path");
$msg = "file uploaded successfully ";
$query = "UPDATE users SET avatar_path='$final_file' WHERE id='$id'";
$fire = mysqli_query($con,$query) or die("can not insert file path into database".mysqli_error($con));
$query = "UPDATE likes SET avatar_path='$final_file' WHERE user_id='$id'";
$fire = mysqli_query($con,$query) or die("can not insert file path into database".mysqli_error($con));
$query = "UPDATE photos SET avatar_path='$final_file' WHERE uid='$id'";
$fire = mysqli_query($con,$query) or die("can not insert file path into database".mysqli_error($con));
if ($fire) {
$msg .=" and also inserted into database";
}
# code...
}else{ echo "only jpg,jpeg,png, type format allowed";}
}else{echo "file size is too large";}
}else{echo "please select an image to upload";}
}
}
}
?>
this code used to work on localhost and my upload code is still working and when i inspect my page the avatar path is correct but still the pic is not being shown a broken image is shown i dont know what is being wrong this is the avatar path that is coming
uploads/Un7sL9TwyNzOhco/bhai.jpg
Try adding slash at first like below:
$final_file= "/uploads/$rand_dir_name/$avatar_name";

Extecuting Query With The Condition in PHP

I have a page in which user can update their posts.
I need to update the database with different query(for different Conditions).
But every time I run update using this code, image filename changes automatically (even if I have a condition). Am I doing something wrong?
if(empty($up_image)){
$up_image = $image;
$update_query = "UPDATE posts SET title = '$up_title', image = '$up_image', categories = '$up_categories', tags = '$up_tags', post_data = '$up_post_data', status = '$up_status' WHERE id = $edit_id";
if(mysqli_query($con, $update_query)){
$msg = "Post has been Updated";
$path1 = "img/$up_image";
header("refresh:1;edit-post.php?edit=$edit_id");
if(move_uploaded_file($up_tmp_name, $path1)){
copy($path1, "../$path1");
}
}
else{
$error = "Unable to Update Post";
}
}
if(!empty($up_image)){
$up_image = preg_replace('/\s+/','',$up_image);
$image_size = $_FILES['image']['size'];
$allowed_img_ext = array("jpg", "jpeg", "png", "bmp");
$ext = pathinfo($up_image, PATHINFO_EXTENSION);
$trimed_img_name = pathinfo($up_image, PATHINFO_FILENAME);
if(in_array($ext, $allowed_img_ext))//check valid file extension
{
if($image_size < 2097152) {
$ren_image = substr($trimed_img_name,0,3)."".substr($title,0,11)."_".date("mj")."_".date("Y")."_".date("His").".".$ext;
$path = "img/".$ren_image;
$update_query = "UPDATE posts SET title = '$up_title', image = '$ren_image', categories = '$up_categories', tags = '$up_tags', post_data = '$up_post_data', status = '$up_status' WHERE id = $edit_id";
}
else{
$img_error = "Please Upload the Image File Size Less than 2 MB";
}
}
else{
$img_error = "Invalid Image File";
}
if(mysqli_query($con, $update_query)){
$msg = "Post has been Updated";
header("refresh:1;edit-post.php?edit=$edit_id");
if(move_uploaded_file($up_tmp_name, $path)){
copy($path, "../$path");
}
}
else{
$error = "Unable to Update Post";
}
} //End
So I removed $up_image = $image; and image = $up_image section from first query now it is working. Thanks for your comment

Profile picture only displays black box with an "X" inside

I am trying to set up a profile page where user can upload a profile picture. The problem I a having is that when the status is changed from 1 to 0 the image changes from a default profile image to a small black box with an "x" in it. Everything else works fine. I thought it might be the css but it is not. If anyone can assist, it would greatly appreciated. Thank you.
Profile.php:
<?php
$id= $_GET['id'];
$sql = "SELECT * FROM user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$sqlImg = "SELECT * FROM profileImg WHERE id='$id'";
$resultImg = mysqli_query($conn, $sqlImg);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
echo "<div class='userProfileImage'>";
if ($rowImg['status'] == 0 ) {
echo "<img src='images/profile".$id.".jpg'>";
} else {
echo "<img src='images/profile_default.jpg'>";
}
echo "<p>".$row['first']."</p>";
echo "</div>";
}
}
} else {
echo "There are no users yet!";
}
uploadProfile.php:
<?php
session_start();
include '../dbh.php';
$id = $_SESSION['id'];
$userID = $id;
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'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'gif', 'png', 'mov', 'mpeg4', 'mp4', 'avi', 'wmv', 'mpegps', 'flv', '3gpp', 'webm');
if (in_array($fileActualExt, $allowed)) {
if ($fileERROR === 0) {
if ($fileSize < 500000) {
$fileNameNew = "profile".$id.".".$fileActualExt;
$fileDestination = '../uploads/'.$fileNameNew;
$sql = "UPDATE profileImg SET status=0 WHERE id='$id'";
$result = mysqli_query($conn, $sql);
move_uploaded_file($fileTmpName, $fileDestination);
header("Location: ../profile.php?id=$userID");
} else {
echo "Your file is too large";
}
} else {
echo "There was an error uploading your file";
}
} else {
echo "You cannot upload files of this type";
}
}
?>
Files are being uploaded to uploads as line below
$fileDestination = '../uploads/'.$fileNameNew;
and img src is
echo "<img src='images/profile".$id.".jpg'>";
Please update you code.
Edit: you are allowing multiple extensions to be uploaded and on profile.php single extension is used to load the picture.

image's table creates differend foreign keys

I have a code which inserts into more 3 tables . what happens is that if I create a new account at the same time I upload images for that account in the images table . The code does it very well but now the problem is it gives each image a unique referenced user_Id yet all images uploaded for that user should be with the same Id from the user table .I am using a relational database where by the user table has a primary key user_id which is referenced to other tables as their foreign key . bellow is my code : ant help will be appreciated .
<?php
#connect to the db
require_once('db.inc.php');
?>
<?php
#code to deal with the picture uploads
#target folder
$target = 'image_uploads/';
if(isset($_FILES['image_name'])===true){
$files = $_FILES['image_name'];
for($x = 0 ; $x < count($files['name']); $x++){
$name = $files['name'][$x] ;
$temp_name = $files['tmp_name'][$x];
#extention filter it takes only the extension want
$allowed ='gif,png,jpg,pdf';
$extension_allowed= explode(',',$allowed );
$file_extention = pathinfo($name, PATHINFO_EXTENSION);
if(array_search($file_extention,$extension_allowed)){
}else {
echo 'We only allow gif, png ,jpg';
exit();
} #extention filter ends here
#check the size of the image
$file_size = $files['size'][$x];
if($file_size > 2097152){
echo 'The file should be lesS than 2MB';
exit();
}
#check the size of the image ends here
#Rename images
$sub = substr(md5(rand()),0,7);
#the above generates char and numbesr
$rand = rand(0,100000);
$rename = $rand.$sub.$name;
#Rename images ends here
$move = move_uploaded_file($temp_name,$target.$rename);
#code to deal with the picture uploads ends here
?>
<?php
$date_created= date('y-m-d h:i:s a');
$username=(isset($_POST['username']))? trim($_POST['username']): '';
$Previllage =(isset($_POST['Previllage']))? trim($_POST['Previllage']): '';
#second tanble values
$title=(isset($_POST['title']))? trim($_POST['title']): '';
$firstname=(isset($_POST['firstname']))? trim($_POST['firstname']): '';
$lastname=(isset($_POST['lastname']))? trim($_POST['lastname']): '';
$client_code=(isset($_POST['client_code']))? trim($_POST['client_code']): '';
$job_approval=(isset($_POST['job_approval']))? trim($_POST['job_approval']): '';
$address=(isset($_POST['address']))? trim($_POST['address']): '';
$cell=(isset($_POST['cell']))? trim($_POST['cell']): '';
$tel=(isset($_POST['tel']))? trim($_POST['tel']): '';
$email=(isset($_POST['email']))? trim($_POST['email']): '';
$company=(isset($_POST['company']))? trim($_POST['company']): '';
$province=(isset($_POST['province']))? trim($_POST['province']): '';
$username= substr(md5(rand()),0,7);
$Pas=substr(md5(rand()),0,4);
$Password =(md5($Pas));
$user =(isset($_POST['$user']))? trim($_POST['$user']): '';
$ip_address = $_SERVER['REMOTE_ADDR'];
try{
$query="INSERT INTO tish_user(username,Password,Previllage,date_created)
VALUES(:username,:Password,:Previllage,:date_created)";
$insert = $con->prepare($query);
$insert->execute(array(
':username'=>$username,
':Password'=>$Password,
':Previllage'=>$Previllage,
':date_created'=>$date_created));
#end of first table
################################################
#You select the first Id and put it in a variable then
$id_last = ("SELECT LAST_INSERT_ID()");
$result =$con->prepare($id_last);
$result->execute();
$last_id = $result->fetchColumn();
############################## Last Id query Ends here
#insert into clientinfo table
$clientinfor="INSERT INTO tish_clientinfo(title,firstname,lastname,user_id)
VALUES(:title,:firstname,:lastname,$last_id)";
$clientinfor_insert = $con->prepare($clientinfor);
$clientinfor_insert->execute(array(
':title'=>$title,
':firstname'=>$firstname,
':lastname'=>$lastname));
#end of clien infor
################################################
$security="INSERT INTO tish_security(ip_address,user_id)
VALUES(:ip_address,$last_id)";
$security_insert = $con->prepare($security);
$security_insert->execute(array(
':ip_address'=>$ip_address));
##########################end of security
############ images
$images ="INSERT INTO tish_images(user_id,image_name,date_registered)
VALUES($last_id,:image_name,:date_registered)";
$images_insert = $con->prepare($images);
$images_insert->execute(array(
':image_name'=>$rename,
':date_registered'=>$date_created));
############# property table##########################################################
/*$property ="INSERT INTO tish_propertyinfo(user_id,date_registered)
VALUES($last_id,:date_registered)";
$property_insert = $con->prepare($images);
$property_insert->execute(array(':date_registered'=>$date_created));
*/}catch(PDOException $e){
echo $e->getMessage();
}
}
}
?>
Is there a auto increment on user_id in the image table? And checknwether $last_id contains anything, I would thinkni is NULL.

Categories