I have row that contains (id, name, pic), I can delete this row from the database, but cannot delete the image from the file server.
Below code should delete the image file:
if(isset($_GET["delete"])){
$pi=$_GET["delete"];
$qry="delete from item where id=".$_GET["delete"];
$de = mysqli_query($conn,$qry);
$filetmp = $_FILES["pic"]["tmp_name"];
// $filename = $_FILES["pic"]["name"];
$qr ="SELECT id FROM item where id='$pi'";
$res = mysqli_query($conn,$qr);
while($row = mysqli_fetch_array($res)){
$id = $row["id"];
}
$path = "uploads/$id.jpg";
//move_uploaded_file($filetmp,$path);
$fpath = "images_upload/Uitem/$path";
unlink($fpath); // delete file
}
you'll have to use the path on your server to delete the image, not the image url.
Like
unlink('/var/www/test/'.$fpath);
Related
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...
<?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.
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);
}
}
Below is the code that should delete the image file.
I have row that contains (id, name, pic), I can delete this row from database,
but did not delete the image from file.
if(isset($_GET["delete"])){
$pic=$_GET["pic"];
$qry="delete from section where id=".$_GET["delete"];
$de = mysqli_query($conn,$qry);
$filetmp = $_FILES["pic"]["tmp_name"];
// $filename = $_FILES["pic"]["name"];
$name = $_POST["name"];
$qr ="SELECT id FROM section ORDER BY id ASC";
$res = mysqli_query($conn,$qr);
$path = "uploads/$id.jpg";
//move_uploaded_file($filetmp,$path);
$fpath = "/images_upload/$path";
unlink("$fpath");
}
I appreciate any help.
$path = "uploads/$id.jpg";
you must assign a value of $id
I would like to use the results of a MYSQL query and generate a batch of QR Codes have the following php script via PhpQrCode. What I need is simply display the list of barcodes generated on HTML page. This is what I wrote so far:
<?php
include "qrlib.php";
require "conf/config.php";
$con = mysql_connect(DBSERVER,DBUSER,DBPASS);
mysql_select_db(DBNAME, $con);
$barcodes = mysql_query( "SELECT Description FROM dbo_sensorsandparts ORDER BY ID ASC");
while ($row = mysql_fetch_array($barcodes))
{
echo "<html>";
echo "<img src=";
QRcode::png ($row['Description']);
echo ">";
}
?>
The query is correct since I tested it out but I only get a blank page with a sort of broken image. Can someone help me as to what I am doing wrong please?
Thanks
SOLVED as follows:
<?php
require "conf/config.php";
$con = mysql_connect(DBSERVER,DBUSER,DBPASS);
mysql_select_db(DBNAME, $con);
$barcodes = mysql_query( "SELECT Description FROM dbo_sensorsandparts ORDER BY ID ASC");
//set it to writable location, a place for temp generated PNG files
$PNG_TEMP_DIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
//html PNG location prefix
$PNG_WEB_DIR = 'temp/';
include "qrlib.php";
//ofcourse we need rights to create temp dir
if (!file_exists($PNG_TEMP_DIR))
mkdir($PNG_TEMP_DIR);
$filename = $PNG_TEMP_DIR.'label.png';
while ($row = mysql_fetch_array($barcodes))
{
$filename = $PNG_TEMP_DIR.'label'.$row['Description'].'.png';
QRcode::png($row['Description'], $filename);
echo '<img src="'.$PNG_WEB_DIR.basename($filename).'" /><hr/>';
echo $filename;
}
?>
To render the image in the html page, hold the returned QRcode image in a location and then specify it as a link in src attribute of <img> tag.
If QRcode::png returns the raw image data, use data URIs to display:
$qr_code = base64_encode(QRcode::png ($row['Description']));
$src = 'data: image/png;base64,'.$qr_code;
echo '<img src="', $src, '">';
Solved as follows:
<?php
require "conf/config.php";
$con = mysql_connect(DBSERVER,DBUSER,DBPASS);
mysql_select_db(DBNAME, $con);
$barcodes = mysql_query( "SELECT Description FROM dbo_sensorsandparts ORDER BY ID ASC");
//set it to writable location, a place for temp generated PNG files
$PNG_TEMP_DIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
//html PNG location prefix
$PNG_WEB_DIR = 'temp/';
include "qrlib.php";
//ofcourse we need rights to create temp dir
if (!file_exists($PNG_TEMP_DIR))
mkdir($PNG_TEMP_DIR);
$filename = $PNG_TEMP_DIR.'label.png';
while ($row = mysql_fetch_array($barcodes))
{
$filename = $PNG_TEMP_DIR.'label'.$row['Description'].'.png';
QRcode::png($row['Description'], $filename);
echo '<img src="'.$PNG_WEB_DIR.basename($filename).'" /><hr/>';
echo $filename;
}
?>
I have stored the PNGs as files via variable $filename.