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...
Related
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
I currently created a system that allowed a user to upload a photo only. The photo the already upload can be replaced if the user want to change it.
The current code shows that there's no error in this function. The URL updated at MySQL database. But the problem is the image doesn't update. Below is my current code:
update_photo_before.php
<?php
require_once '../../../../config/configPDO.php';
$report_id = $_POST['report_id'];
$last_insert_id = null;
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png");
//File extension
$ext = strtolower(pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION));
//Check extension
if(in_array($ext, $allowed_extensions)) {
$defID = "before_" . $report_id;
$imgPath = "images/$defID.png";
$ServerURL = "http://172.20.0.45/tgotworker_testing/android/$imgPath";
$query = "UPDATE ot_report SET photo_before = '$ServerURL', time_photo_before = GETDATE() WHERE report_id = :report_id";
$sql = $conn->prepare($query);
$sql->bindParam(':report_id', $report_id);
$sql->execute();
if ($sql){
move_uploaded_file($_FILES['uploadFile']['name'], $imgPath); //line 28
echo "<script>alert('Saved')</script>";
header("Location: view_task.php?report_id=".$_POST['report_id']);
}else{
echo "Error!! Not Saved";
}
} else {
echo "<script>alert('File not allowed')</script>";
header("Location: view_task.php?report_id=".$_POST['report_id']);
}
?>
My folder images are located at 'tgotworker_testing' --> 'android' --> 'images'.
For update_photo_before.php:
'tgotworker_testing' --> 'pages' --> 'dashboard' --> 'engineer' --> 'view_task' --> 'update_photo_before.php'
Can anyone fix my problem? Thanks!
You check to see if the database gets updated, but not if the image is saved to the server.
move_uploaded_file() returns true on success and false on failure. So you can do a similar test as you have for $sql in your code.
<?php
require_once '../../../../config/configPDO.php';
$report_id = $_POST['report_id'];
$last_insert_id = null;
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png");
//File extension
$ext = strtolower(pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION));
//Check extension
if(in_array($ext, $allowed_extensions)) {
$defID = "before_" . $report_id;
$imgPath = "images/$defID.png";
$ServerURL = "http://172.20.0.45/tgotworker_testing/android/$imgPath";
// Check if image is uploaded to folder
if(move_uploaded_file($_FILES['uploadFile']['name'], $imgPath) === true) {
// If upload succeeds, then update database
$query = "UPDATE ot_report SET photo_before = '$ServerURL', time_photo_before = GETDATE() WHERE report_id = :report_id";
$sql = $conn->prepare($query);
$sql->bindParam(':report_id', $report_id);
$sql->execute();
// Check if database updated
if (!$sql){
echo "Error!! Database not updated.";
} else {
// Success!
header("Location: view_task.php?report_id=".$_POST['report_id']);
}
} else {
// Could not upload file
echo "Error!! Could not upload file to server.";
}
}
When PHP can't upload the file it will throw a warning. If you turn on your warnings while you are debugging, it should give you the reason why it's not working and you will be better able to solve the problem.
Put these lines at the top of the script to show all warnings and errors:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
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);
}
}
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);
I found a simple script on internet on how to upload files in php.
<?php
require 'config.php';
if (isset ( $_SERVER ['REQUEST_METHOD'] ) == 'POST') {
// when submit button is clicked
if (isset ( $_POST ['submit'] )) {
// get user's data
$name = $_POST ['name'];
$email = $_POST ['email'];
$images = "";
// check if user has added images
if(strlen(($_FILES ['upload'] ['tmp_name'] [0])) != 0){
$upload_dir = "images/";
// move all uploaded images in directory
for ($i = 0; $i < count($_FILES['upload']['name']); $i++) {
$ext = substr(strrchr($_FILES['upload']['name'][$i], "."), 1);
// generate a random new file name to avoid name conflict
$fPath = md5(rand() * time()) . ".$ext";
$images .= $fPath.";";
$result = move_uploaded_file($_FILES['upload']['tmp_name'][$i], $upload_dir . $fPath);
}
}else {
// if user doesn't have any images, add default value
$images .= "no images";
}
// write the user's data in database
// prepare the query
$query = "INSERT INTO users(name, email,images) VALUES
('$name', '$email','$images')";
// TODO check if the user's informations are successfully added
// in the database
$result = mysql_query ( $query );
}
}
?>
This script does a really good job overall but the only problem is that when I upload image files or pdf they open up in a new tab, they do not download. How do I make the uploaded image files automatically download when the download link is clicked on? Thanks in advance.
Add the download link as follows
<a href="link/to/your/download/image" download>Download link</a>
Add the following code in apache config
<Location "/images">
<Files *.*>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>
</Location>