update image if uploaded else use previosly stored image - php

<?php
include '../db_conx.php';
$id = $_POST['id'];
$file = addslashes(file_get_contents($_FILES["college_image"]["tmp_name"]));
$insert_data1 = mysqli_real_escape_string($db_conx,$_POST['college_overview']);
$insert_data2 = mysqli_real_escape_string($db_conx,$_POST['college_courses']);
$insert_data3 = mysqli_real_escape_string($db_conx,$_POST['college_facilities']);
$test = "UPDATE college_details SET college_overview='$insert_data1', college_courses='$insert_data2', college_facilities='$insert_data3',college_image = '$file' where id = '$id' ";
if (mysqli_query($db_conx,$test)){
header("Location:college.php?success");
}
{
echo("Error description: " . mysqli_error($db_conx));
}
?>
Whenever i try to update without uploading a new image the previously stored image gets removed. How do i keep the old image when no file is uploaded

You can check whether the upload file is empty or not using simple if else statement and reformat your sql statement accordingly:
if(!file_exists($_FILES["college_image"]["tmp_name"]) ||
!is_uploaded_file($_FILES["college_image"]["tmp_name"])) {
$test = "UPDATE college_details SET college_overview='$insert_data1',
college_courses='$insert_data2', college_facilities='$insert_data3',
where id = $id ";
//No file is uploaded, we skip updating the image.
}else{
//Upload File is there, we update the image file in the database
$test = "UPDATE college_details SET college_overview='$insert_data1',
college_courses='$insert_data2', college_facilities='$insert_data3',
college_image = '$file' where id = $id ";
}
Your code is vulnerable to sql injection. Use prepared statement to update your data.

Related

file upload while edit row in database

I am working on simple CRUD and I am facing difficulty with the "Edit section"
Long story short:
I have MySQL base with records, I am printing them on the front page, I have added two buttons for "Add new record" via <form and "Edit record" where I can edit any record.
The problem: in the "Add" section I can upload files during adding a new record.
here is the code for uploading a file in insert.php
// Include the database configuration file
include 'db.php';
$statusMsg = '';
// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
}
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf','doc','xlsx');
if(in_array($fileType, $allowTypes)){
}
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
}
Via this one, I am uploading the file on the server and making the record into the database as the filename.
I would like to use the same way while editing records in order if the user wants to upload a file later, but when I use the same code I am getting
Warning: Undefined array key "file" in C:\xampp\htdocs\crud\edit.php on line 12
Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\crud\edit.php on line 12
Here is my edit.php code:
<?php
// include database connection file
include_once("config.php");
// Check if form is submitted for user update, then redirect to homepage after update
if(isset($_POST['update']))
{
$id = $_POST['id'];
$toolnr=$_POST['toolnr'];
$status=$_POST['status'];
$toolname=$_POST['toolname'];
$serial=$_POST['serial'];
$usedat=$_POST['usedat'];
$owner=$_POST['owner'];
$calibrated=$_POST['calibrated'];
$nextcalibration=$_POST['nextcalibration'];
$vendors=$_POST['vendors'];
// update tools data
$result = mysqli_query($mysqli, "UPDATE tools SET toolnr='$toolnr',status='$status',toolname='$toolname',serial='$serial',usedat='$usedat',owner='$owner',calibrated='$calibrated',nextcalibration='$nextcalibration', vendors='$vendors', file_name = '$fileName' WHERE id=$id");
// Redirect to homepage to display updated tools in list
header("Location: index.php");
}
?>
<?php
// Display selected tool data based on id
// Getting id from url
$id = $_GET['id'];
// Fetech tool data based on id
$result = mysqli_query($mysqli, "SELECT * FROM tools WHERE id=$id");
while($user_data = mysqli_fetch_array($result))
{
$toolnr = $user_data['toolnr'];
$status = $user_data['status'];
$toolname = $user_data['toolname'];
$serial = $user_data['serial'];
$usedat = $user_data['usedat'];
$owner = $user_data['owner'];
$calibrated = $user_data['calibrated'];
$nextcalibration = $user_data['nextcalibration'];
$vendors = $user_data['vendors'];
}
?>
and here is the HTML pcs:
<tr>
<td>File upload:</td>
<td><input type="file" name="file" ></td>
</tr>
---- update ------
Here is the full edit.php code:
<?php
// include database connection file
include_once("config.php");
// Include the database configuration file
include 'db.php';
$statusMsg = '';
// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
}
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf','doc','xlsx');
if(in_array($fileType, $allowTypes)){
}
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
}
// Check if form is submitted for tool update, then redirect to homepage after update
if(isset($_POST['update']))
{
$id = $_POST['id'];
$toolnr=$_POST['toolnr'];
$status=$_POST['status'];
$toolname=$_POST['toolname'];
$serial=$_POST['serial'];
$usedat=$_POST['usedat'];
$owner=$_POST['owner'];
$calibrated=$_POST['calibrated'];
$nextcalibration=$_POST['nextcalibration'];
$vendors=$_POST['vendors'];
// update tool data
$result = mysqli_query($mysqli, "UPDATE tools SET toolnr='$toolnr',status='$status',toolname='$toolname',serial='$serial',usedat='$usedat',owner='$owner',calibrated='$calibrated',nextcalibration='$nextcalibration', vendors='$vendors',file_name = '$fileName' WHERE id=$id");
// Redirect to homepage to display updated tool in list
header("Location: index.php");
}
?>
<?php
// Display selected tool data based on id
// Getting id from url
$id = $_GET['id'];
// Fetech tool data based on id
$result = mysqli_query($mysqli, "SELECT * FROM tools WHERE id=$id");
while($user_data = mysqli_fetch_array($result))
{
$toolnr = $user_data['toolnr'];
$status = $user_data['status'];
$toolname = $user_data['toolname'];
$serial = $user_data['serial'];
$usedat = $user_data['usedat'];
$owner = $user_data['owner'];
$calibrated = $user_data['calibrated'];
$nextcalibration = $user_data['nextcalibration'];
$vendors = $user_data['vendors'];
}
?>
Maybe I am working in the wrong way somehow...

What's wrong?, I want to copy the image file to my other directory after upload, and input it to the mysql database too

this is my code
<?php
include 'koneksi.php';
$judul_artikel = $_POST['judul_artikel'];
$isi_artikel = $_POST['isi_artikel'];
$tanggal_artikel = date('Y-m-d');
$tag_artikel = $_POST['tag_artikel'];
$filetmp = $_FILES["gambar_artikel"]["tmp_name"];
$filename = $_FILES["gambar_artikel"]["name"];
$filetype = $_FILES["gambar_artikel"]["type"];
$filepath = "img/".$filename;
move_uploaded_file($filetmp, $filepath);
$query = mysql_query('INSERT INTO artikel(judul_artikel,isi_artikel,tanggal_artikel,tag_artikel,gambar_artikel) VALUES ("'.$judul_artikel.'","'.$isi_artikel.'","'.$tanggal_artikel.'","'.$tag_artikel.'","'.$filepath.'")')or die(mysql_error());
if ($query) {
header('location:artikel.php?notif=berhasil');
} else {
header('location:artikel.php?notif=gagal');
}
?>
the problem I face is, I want to copy the image file to another directory after I upload it, and input it into the mysql database too, but when I execute, the file that I upload is not copied in the directory that I want, and is not inputted into the mysql database, how to handle it ?
try to wrap it inside if condition like this
if(move_uploaded_file($filetmp, $filepath)){
echo "success";
}else{
echo "failed";
}
and make sure you set the folder permission

Update file in database and upload file

thank you in advance for your help, i need to make a system were i can upload and update a file into my database record. To do so i made this code but for some reason i cant seem to see what i have done wrong i can update the "status and so on" but the file is not uploaded into my desired directory and the record is missing in my database too, so all the rest works just fine, except the file itself, does not get updated. Here is my code, again thanks in advance!
<?php
if(isset($_POST['submit_btn']))
{
if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target)) {
require 'modules/conn.php';
$target = "../account-files/";
$target = $target . basename( $_FILES['Filename']['name']);
}
$id = $_REQUEST['id'];
$status = $_REQUEST['status'];
$counts = $_REQUEST['counts'];
$Filename=basename( $_FILES['Filename']['name']);
$query = mysqli_query($conn,"UPDATE files SET id ='".$_POST['id']."', status ='".$_POST['status']."', counts ='".$_POST['counts']."', Filename ='".$_POST['Filename']."' WHERE id = '".$id."'") or die(mysqli_error($conn));
header("location: ../my-account/");
}
?>
Everything else gets updated in my database, but as i said, the file and the record of the file name does not, also its not uploaded into my directory. Please help me, an example would be very much appreciated.
Updated code i can get the records into the database but still no upload into the directory.
$target = "../account-files/";
$target = $target . basename( $_FILES['Filename']['name']);
if(isset($_POST['submit_btn']))
{
move_uploaded_file($_FILES['Filename']['tmp_name'], $target);
require 'modules/conn.php';
$id = $_REQUEST['id'];
$status = $_REQUEST['status'];
$counts = $_REQUEST['counts'];
$Filename=basename( $_FILES['Filename']['name']);
$query = mysqli_query($conn,"UPDATE files SET id = $id, status = '$status', counts = $counts , Filename = '$Filename' WHERE id = '$id'") or die(mysqli_error($conn));
header("location: ../my-account/");
}
This last solution is correct i hope i can contribute also to other members, see solution credits bellow at the correct reply to my post, that guy rocks! Thumbs up so what was the error? Simple, the path i had was wrong...
this one is wrong:
$target = "../account-files/";
This is correct and fixes all
$target = "account-files/";
Do you really have the POST['Filename']? I think you should put the variables in you query instead of .POST
Try the code below:
if(isset($_POST['submit_btn']))
{
$target_dir = "../account-files/";
$target_file = $target_dir . basename( $_FILES['Filename']['name']);
move_uploaded_file($_FILES['Filename']['tmp_name'], $target_file);
require 'modules/conn.php';
$id = $_REQUEST['id'];
$status = $_REQUEST['status'];
$counts = $_REQUEST['counts'];
$Filename=basename( $_FILES['Filename']['name']);
$query = mysqli_query($conn,"UPDATE files SET id = $id, status =
'$status', counts = $counts , Filename = '$Filename' WHERE id =
'".$id."'") or die(mysqli_error($conn));
header("location: ../my-account/");
}
And also please make sure that you have the enctype="multipart/form-data" on your form tag.
You make some mistakes:
how you can upload the file first and then determine the target
why are you updating id? while id is its primary key
i
if(isset($_POST['submit_btn'])){
$target = "../account-files/";
$fname = $_FILES['filename']['name'];
if(!empty($target) && !empty($fname)){
move_uploaded_file($_FILES['filename']['tmp_name'], $target.$fname);
}
}

Uploading 1000 images via url using PHP

I want to upload 1000 images in just one click via URL. I have 1000 Image URLs stored in MYSQL database.
So please any one give me PHP code to upload that 1000 images via URL through mysql database.
Currently I am using the bellow code:-
It upload one image per click by posting URL of image...
But i want to upload 1000 image in one click by getting URLs from databse
$result = mysql_query("SELECT * FROM thumb") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
echo "<div>";
$oid = $row['tid'];
$th= $row['q'];
echo "</div>";
$thi = $th;
$get_url = $post["url"];
$url = trim('$get_url');
if($url){
$file = fopen($url,"rb");
$directory = "thumbnail/";
$valid_exts = array("php","jpeg","gif","png","doc","docx","jpg","html","asp","xml","JPEG","bmp");
$ext = end(explode(".",strtolower(basename($url))));
if(in_array($ext,$valid_exts)){
$filename = "$oid.$ext";
$newfile = fopen($directory . $filename, "wb");
if($newfile){
while(!feof($file)){
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}
echo 'File uploaded successfully';
echo '**$$**'.$filename;
}
else{
echo 'File does not exists';
}
}
else{
echo 'Invalid URL';
}
}
else{
echo 'Please enter the URL';
}
}
Thanks a lot.... …
The code you have is outdated and a lot more complex than needed. This is not a site where you get code because you ask, this is a learning environment.
I'll give you an example on which you can continue:
// Select the images (those we haven't done yet):
$sItems = mysql_query("SELECT id,url FROM thumb WHERE imported=0") or die(mysql_error());
// Loop through them:
while( $fItems = mysql_fetch_assoc($sItems) ){
$imgSource = file_get_contents($fItems['url']); // get the image
// Check if it didn't go wrong:
if( $imgSource!==false ){
// Which directory to put the file in:
$newLocation = $_SERVER['DOCUMENT_ROOT']."/Location/to/dir/";
// The name of the file:
$newFilename = basename($fItems['url'], $imgSource);
// Save on your server:
file_put_content($newLocation.$newFilename);
}
// Update the row in the DB. If something goes wrong, you don't have to do all of them again:
mysql_query("UPDATE thumb SET imported=1 WHERE id=".$fItems['id']." LIMIT 1") or die(mysql_error());
}
Relevant functions:
file_get_contents() - Get the content of the image
file_put_contents() - Place the content given in this function in a file specified
basename() - given an url, it gives you the filename only
Important:
You are using mysql_query. This is deprecated (should no longer be used), use PDO or mysqli instead
I suggest you make this work from the commandline and add an echo after the update so you can monitor progress

deleting image from the storage folder in php

I want to delete the image from the storage folder at the time of deleting from the database also.
The image file is getting deleted from database but unable to delete from server storage folder.
The image is getting stored in http://url.com/foldername/files/newsletter
The below is the code i used..
<?php
$id = intval($_REQUEST['id']);
include 'db/connection.php';
$sql1 = mysql_query("select * from tablename where id=$id");
$results=mysql_fetch_array($sql1);
if($results["file"]!="") {
$image=$results["file"];
unlink("../files/newsletter/".$image);
}
$sql = "delete from tablename where id=$id";
$result = #mysql_query($sql);
if ($result){
echo json_encode(array('success'=>true));
} else {
echo json_encode(array('msg'=>'Some errors occured.'));
}
?>
Plz help in resolving..Thank you
try to add document root with your code to something like code below.
$imageWithPath = $_SERVER['DOCUMENT_ROOT']."/files/newsletter/".$image;
#unlink($imageWithPath);
Can you print out what your $results["file"] value is and check.
You are using mysql_fetch_array it should be inside while loop
$sql1 = mysql_query("select * from tablename where id=$id");
while($row = mysql_fetch_array($sql1)){
$image = $row["file"];
//make sure below path is correct.
$image_path = $_SERVER['DOCUMENT_ROOT'].'/foldername/files/newsletter/'.$image;
echo $image_path;//you can compare if the path is correct or not
//Also check if file exists here
if(file_exists(image_path)){
unlink($image_path);
}
else{
echo 'file doesnot exist';
}
}
Also you will need to have permissions to be able to delete the file. Make sure the apache or user that runs your script file have correct permission or ownership of the file.

Categories