trying to upload image and have it update mysql - php

Whenever I try to upload a file using a form and have it insert the file into mysql, I get these errors-
Notice: Undefined index: file in
/home/sgas/public_html/x/agentpage.php on line 300
Notice: Undefined index: file in
/home/sgas/public_html/x/agentpage.php on line 305
Notice: Undefined index: file in
/home/sgas/public_html/x/agentpage.php on line 310
I have looked over the names and they seem to all be right so I have no idea whats wrong right now :/.
Here is the code starting at the form where you upload the image.
<td align="right" valign="top" class="bodymaintextalt">applicable document</td>
<td>
<input name="file" type="file" id="file" size="35">
</tr>
<tr>
<td align="right" valign="top" class="bodymaintextalt">received</td>
<td>
<input name="received" type="text" id="received" value="$">
</td>
</tr>
<tr>
<td align="right" valign="top" class="bodymaintextalt">paid</td>
<td>
<input name="paid" type="text" id="paid" value="$">
</td>
</tr>
<tr>
<td align="right" valign="top"> </td>
<td>
<div align="right">
<input type="submit" name="Submit32" value="Submit">
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
if ('POST' === $_SERVER['REQUEST_METHOD']){
$con = mysql_connect("localhost","xxx","xxxxx");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xxxxx", $con);
$target = "clientdoc/";
$target = $target . basename( $_FILES['file']['agentclient']);
$date = $_POST['date'];
$propertydescription = $_POST['propertydescription'];
$transactiontype = $_POST['transactiontype'];
$applicabledocument = ($_FILES['file']['agentclient']);
$received = $_POST['received'];
$paid = $_POST['paid'];
//Writes the to the server
if(move_uploaded_file($_FILES['file']['tmp_name'], $target)){
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['agentclient']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
$sql = mysql_query("INSERT INTO `transactions` (`date`, `agentclient`, `propertydescription`, `transactiontype`, `applicabledocument`, `received`, `paid`)
VALUES ('$date', '$agentclient', '$propertydescription', '$transactiontype', '$applicabledocument', '$received', '$paid')") or die(mysql_error());
$query = mysql_query($sql);
if ($_SERVER['REQUEST_METHOD'] === 'POST'){
echo "Succesfully added transaction. Updating table...";
echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"48\">";
mysql_close($con);
}
}

your file name is file so change it to agentclient so
<input type="file" name="agentclient" id="file"/>
$target = $target . basename( $_FILES['agentclient']['name']);

Related

file upload (php) two warnings

I am working on small page where I update MySQL records via PHP page, all the functionality is well working but I constantly get warnings for an Undefined array.
Here are the warnings:
Warning: Undefined array key "file" in C:\xampp\htdocs\crud\edit.php on line 11
Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\crud\edit.php on line 11
Warning: Undefined array key "file" in C:\xampp\htdocs\crud\edit.php on line 22
Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\crud\edit.php on line 22
I was looking at many topics like this but did not manage to fix my own one...
Here is the code of edit.php
include 'db.php';
// 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)){
}
I have also a pcs of HTML for that in <form:
<form name="update_user" method="post" action="edit.php" enctype="multipart/form-data" >
<tr>
<td>Нов сертификат:</td>
<td><input type="file" name="file" ></td>
</tr>
I have a feeling that I missed something very simple.
----- update -------
here is my full code: in one file I put php with the html
// include database connection file
include_once("config.php");
//тук стартирам за фаил ъплоад
// Include the database configuration file
include 'db.php';
// 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 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 user 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 user in list
header("Location: index.php");
}
?>
<?php
// Display selected user data based on id
// Getting id from url
$id = $_GET['id'];
// Fetech user 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'];
$momenten = $user_data['file_name'];
}
?>
<html>
<head>
<title>Актуализация</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<center> <img src="logo-ottobock.png" alt="OttobockLogo"> </center>
<hr> <br>
<center> <img src="notification.png" alt="Warning"> </center>
<center> <i> <p style="color:red;"> В момента работите с най-високо ниво на достъп, моля бъдете внимателни. <br> Всички направени от Вас промени са необратими. <p> </i> </center>
</head>
<body>
<br/><br/>
<center> <form name="update_user" method="post" action="edit.php" enctype="multipart/form-data" >
<table border="0" class="table table-striped" >
<tr>
<td>Номер</td>
<td><input type="text" name="toolnr" class="form-control" value=<?php echo $toolnr;?>></td>
</tr>
<tr>
<td>Статус</td>
<td>
<select name="status" id="status" class="form-control" required>
<?php
include "dbConn.php";
$records = mysqli_query($db, "SELECT status FROM tools WHERE id=$id UNION SELECT currentstatus FROM statuses");
while($data = mysqli_fetch_array($records))
{
echo "<option value='". $data['status'] ."'>" .$data['status'] ."</option>";
}
?> </select>
</td>
</tr>
<tr>
<td>Найменование</td>
<td><input type="text" name="toolname" class="form-control" value="<?php echo $toolname;?>"></td>
</tr> <br>
<tr>
<td>Сериен номер</td>
<td><input type="text" name="serial" class="form-control" value="<?php echo $serial;?>"></td>
</tr>
<tr>
<td>Локация</td>
<td>
<select name="usedat" id="usedat" class="form-control" required>
<?php
include "dbConn.php";
$records = mysqli_query($db, "SELECT usedat FROM tools WHERE id=$id UNION SELECT locations From whereused");
while($data = mysqli_fetch_array($records))
{
echo "<option value='". $data['usedat'] ."'>" .$data['usedat'] ."</option>";
}
?> </select>
</td>
</tr>
<tr>
<td>Отговорник</td>
<td>
<select name="owner" id="owner" class="form-control" required>
<?php
include "dbConn.php";
$records = mysqli_query($db, "SELECT owner FROM tools WHERE id=$id UNION SELECT responsiblepersons From responsibles");
while($data = mysqli_fetch_array($records))
{
echo "<option value='". $data['owner'] ."'>" .$data['owner'] ."</option>";
}
?> </select>
</td>
</tr>
<tr>
<td>Калибриран на:</td>
<td><input type="date" name="calibrated" class="form-control" value=<?php echo $calibrated;?>></td>
</tr>
<tr>
<td>Следваща</td>
<td><input type="date" name="nextcalibration" class="form-control" value=<?php echo $nextcalibration;?>></td>
</tr>
<tr>
<td>Сертификат</td>
<td><?php echo "<a target = '_blank' href='http://10.171.2.15/crud/uploads/$momenten'> Свали </a>";?></td>
</tr>
<tr>
<td>Нов сертификат:</td>
<td><input type="file" name="file" ></td>
</tr>
<tr>
<td>Калибрира се при</td>
<td>
<select name="vendors" id="vendors" class="form-control" required>
<?php
include "dbConn.php";
$records = mysqli_query($db, "SELECT vendors FROM tools WHERE id=$id UNION SELECT vendoren FROM vendors");
while($data = mysqli_fetch_array($records))
{
echo "<option value='". $data['vendors'] ."'>" .$data['vendors'] ."</option>";
}
?> </select>
</td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" class="btn btn-success" value="Запис">
<a href="index.php" class="btn btn-danger" >Отказ</a> </td>
</tr>
</table>
</form> </center>
</body>
Posting working code:
final-fixed code (only php part). The problem was that the part of the code responsible for file upload was out of the if statement
<?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'];
// 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)){
}
// update user 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 user in list
header("Location: index.php");
}
?>

PHP - uploading new profile images. cannot set new img user variable, and cannot insert img into the database [duplicate]

This question already has answers here:
MySQL Insert query doesn't work with WHERE clause
(31 answers)
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 4 years ago.
I dont understand why this isnt working, i have an insert querie, and one to change the Session variable, which both look fine. the actual image goes into the folder fine, it just does not get inserted into the database, nor stored as a session variable and displayed on the page. any help would be very appreciated!
here is the php processing code:
<?php
session_start();
include_once 'dbh-inc.php';
if (isset($_POST['upload'])) {
//gets all info from file to upload using the form//
$file = $_FILES['file'];
//extracting all info from file//
$FileName = $_FILES['file'] ['name'];
$FileTmpName = $_FILES['file'] ['tmp_name'];
$FileSize = $_FILES['file'] ['size'];
$FileError = $_FILES['file'] ['error'];
$FileType = $_FILES['file'] ['type'];
//separating the file name from the file extension, single out extension//
$FileExt = explode('.', $FileName);
//end function gets the last piece of data from an array//
$FileActualExt = strtolower(end($FileExt));
//allowed file types//
$allowed = array('jpg', 'jpeg', 'png');
//checking whether the fileactualext ie. extension types are defined as
allowed//
if (in_array($FileActualExt, $allowed)) {
if ($FileError === 0) {
if ($FileSize < 1000000) {
$FileNameNew = uniqid('', true).".".$FileActualExt;
$FileDestination = 'uploads/'.$FileNameNew;
//inserting into database//
$sql = "INSERT INTO users (user_image) VALUES ('$FileName') WHERE
`user_id`='".$_SESSION["u_id"]."' ;";
mysqli_query($conn, $sql);
//updating session image variable//
$result = mysqli_query($conn, "SELECT * FROM `users` WHERE
`user_id`='".$_SESSION["u_id"]."'");
$row = mysqli_fetch_array($result);
$_SESSION['u_image'] = $row['user_image'];
//inserting into folder//
move_uploaded_file($FileTmpName, $FileDestination);
header("Location: index.php?upload=success");
exit();
} else {
echo "your file is too big!";
}
}
} else {
echo "error uploading file";
}
} else {
echo "you cannot upload files of this type!";
}
and here is the html code for the editing profile page:
<?php include_once 'Header.php';
$uid = ucfirst($_SESSION['u_uid']);
//THIS CODE ONLY EDITS THE VISIBLE PORTION OF A USERS PROFILE//
?>
<table width="398" border="0" align="center" cellpadding="0">
<form class="edit-profile" action="includes/edit-profile-inc.php"
method="POST">
<tr>
<td width="82" valign="top"><div align="left"> <?php echo $uid ?> </div>
</td>
<td height="26" colspan="2"><input type="text" name="uid"
placeholder="New Username"></td>
<td><div align="right">logout</div></td>
</tr>
<tr>
<td width="129" rowspan="5"><img src="<?php echo $picture ?>" width="129"
height="129" alt="no image found"/></td>
<td width="82" valign="top"><div align="left">FirstName:</div></td>
<td width="165" valign="top"><input type="text" name="first"
placeholder="New First name"></td>
</tr>
<tr>
<td valign="top"><div align="left">LastName:</div></td>
<td valign="top"><input type="text" name="last" placeholder="New Last
Name"></td>
</tr>
<tr>
<tr>
<td valign="top"><div align="left">City:</div></td>
<td valign="top"><input type="text" name="city" placeholder="New City">
</td>
</tr>
<tr>
<tr>
<td valign="top"><div align="left">Region: </div></td>
<td valign="top"><input type="text" name="region" placeholder="New
Region"></td>
</tr>
<tr>
<td valign="top"><div align="left">Country:</div></td>
<td valign="top"><input type="text" name="country" placeholder="New
Country"></td>
</tr>
<tr>
<td valign="top"><div align="left">About me: </div></td>
<td valign="top">
<input type="text" name="about" placeholder="About me">
</thgd>
</tr>
<tr>
<td><button type="submit" name="edit">Update profile</button></td>
</tr>
</form>
<form action="uploads-inc.php" method="POST" enctype="multipart/form-data">
<tr>
<td>
<input type="file" name="file" >
<button type="submit" name="upload">Update profile picture</button>
</td>
</tr>
</form>
<p align="center"></p>
<?php
include_once 'Footer.php';
?>
Send help!

when i upload file to phpmyadmin show error in 4 lines

I create this upload form for uploading products to phpmyadmin but when I click on upload button its error in 4 lines:
Notice: Undefined index: file in C:\xampp\htdocs\MyShop\admin_area\insert_product.php on line 102
Notice: Undefined index: file in C:\xampp\htdocs\MyShop\admin_area\insert_product.php on line 103
Notice: Undefined index: file in C:\xampp\htdocs\MyShop\admin_area\insert_product.php on line 104
Notice: Undefined index: file in C:\xampp\htdocs\MyShop\admin_area\insert_product.php on line 105
My html is:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>
Untitled Document
</title>
</head>
<body>
<form action="insert_product.php" method="post" encypt="multipart/form-data">
<table align="center" width="800" >
<tr>
<td>
Insert New Post
</td>
</tr>
<tr>
<td>
<b>
Product title:
</b>
</td>
<td>
<input type="text" name="product_title" required/>
</td>
</tr>
<tr>
<td>
<b>
Product Category:
</b>
</td>
<td>
<select name="product_cat">
<option>Select a Category</option>
<?php
$get_cats = "select * from categories";
$run_cats = mysqli_query($con, $get_cats);
while ($row_cats=mysqli_fetch_array($run_cats)) {
$cat_id = $row_cats['cat_id'];
$cat_title = $row_cats['cat_title'];
echo "<option value='$cat_id'>$cat_title</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td align="right">
<b>
Product Image
</b>
</td>
<td>
<input type="file" name="file" />
</td>
</tr>
<tr>
<td>
<b>
Product Price:
</b>
</td>
<td>
<input type="text" name="product_price" />
</td>
</tr>
<tr>
<td>
<b>
Product Description:
</b>
</td>
<td>
<textarea name="product_desc"></textarea>
</td>
</tr>
<tr>
<td>
<b>
Product keywords:
</b>
</td>
<td>
<input type="text" name="product_keywords" />
</td>
</tr>
<tr>
<td>
<input type="submit" name="insert_post" value="Insert Product" />
</td>
</tr>
</table>
</form>
</body>
</html>
<?php
if(isset($_POST['insert_post'])) {
$product_title = $_POST['product_title'];
$product_cat = $_POST['product_cat'];
$product_price = $_POST['product_price'];
$product_desc = $_POST['product_desc'];
$product_keywords = $_POST['product_keywords'];
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="uploads/";
// new file size in KB
$new_size = $file_size/1024;
$new_file_name = strtolower($file);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);
// new file size in KB
move_uploaded_file($file_loc,$folder.$final_file);
$insert_product = "insert into products (product_cat,product_title,file,type,size,,product_price,product_desc,product_keywords) values ('$product_cat','$product_title','$final_file','$file_type','$new_size','$product_price','$product_desc','$product_keywords')";
$insert_pro = mysqli_query($con, $insert_product);
if($insert_pro) {
echo "<script>alert('Product has been inserted!')</script>";
echo "<script>window.open('insert_product.php','_self')</script>>";
}
}
?>
You need to check isset condition before taking action on $_FILES
if(isset($_FILES['file']['name']))
{
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="uploads/";
// new file size in KB
$new_size = $file_size/1024;
$new_file_name = strtolower($file);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);
// new file size in KB
move_uploaded_file($file_loc,$folder.$final_file);
}
You have typo error in form enctype:
<form action="insert_product.php" method="post" enctype="multipart/form-data">

Adding the row ID to the filename of the uploaded file

I want to add the ID number of the row to the uploaded file file name.
e.g. if the file name is stack.pdf before uploading, after uploading it should change to stack-ID#.pdf.
This is the PHP Codes that is use to upload
$sp=mysqli_connect("localhost","root","","ara");
if($sp->connect_errno){
echo "Error <br/>".$sp->error;
}
$path="pdf/";
if(isset($_POST['upload']))
{
$path=$path.$_FILES['file_upload']['name'];
if(move_uploaded_file($_FILES['file_upload']['tmp_name'],$path))
{
echo " ".basename($_FILES['file_upload']['name'])." has been uploaded<br/>";
echo '<img src="gallery/'.$_FILES['file_upload']['name'].'" width="48" height="48"/>';
$img=$_FILES['file_upload']['name'];
$query="insert into library (path,CreatedTime) values('$img',now())";
if($sp->query($query)){
echo "<br/>Inserted to DB also";
}else{
echo "Error <br/>".$sp->error;
}
}
else
{
echo "There is an error,please retry or ckeck path";
}
}
And this is the form
<form action="accept-file.php" method="post" enctype="multipart/form-data">
<table width="384" border="1" align="center">
<tr>
<td width="108">Select File</td>
<td width="260"><label>
<input type="file" name="file_upload">
</label></td>
</tr>
<tr>
<td><label>
<input type="submit" name="upload" value="Upload File">
</label></td>
<td> </td>
</tr>
</table>
</form>
I will really appreciate your help. Thanks.
Try this:
$uploadFileName = $_FILES['file_upload']['name'];
//get extention of upload file
$attachment_ext = explode('.', $uploadFileName);
$ext_pt = $attachment_ext[1];
//Give a new name for the file
$newName = '123'.$uploadFileName.".".$ext_pt;
$path = "YOURPATHHERE/";
$save_attchment = $path.$newName ; //setting the path
move_uploaded_file($_FILES['file_upload']['tmp_name'], $save_attchment);

Image upload via php and adding details to mysql

So I have searched everywhere and i cannot figure this out at all. I am trying to upload POST info and the image name to SQL and also upload the image to the uploads directory. SQL will update all info except the image line nor will it actually upload the image. Ill post code below
EDIT: I got it to add the file name into the SQL table but still it wont upload file.
FORM info
<table width="100%" border="0">
<tr><form action="specialadd.php" method="post">
<td>Name of Special</td>
<td>Special Price</td>
</tr>
<tr>
<td valign="top">
<input type="text" name="name"></td>
<td><input type="text" name="price"></td>
</tr>
<tr>
<td>Description #1</td>
<td>Description #2</td>
</tr>
<tr>
<td><textarea name="desc1" rows="6" cols="50"></textarea></td>
<td><textarea name="desc2" rows="6" cols="50"></textarea></td>
</tr>
<tr>
<td>Upload Photo</td>
<td> </td>
</tr>
<tr>
<td><input type="file" name="image"></td>
<td><input type="submit" value="Save Your Special"></form></td>
</tr>
</table>
PHP Info
<?php
//This is the directory where images will be saved
$target = "/public_html/uploads";
$target = $target . basename( $_FILES['image']['name']);
//This gets all the other information from the form
$name=$_POST['name'];
$desc1=$_POST['desc1'];
$desc2=$_POST['desc2'];
$price=$_POST['price'];
$image=($_FILES['image']['name']);
// Connects to your Database
include "process/connect.php";
//Writes the information to the database
mysql_query("UPDATE specials
SET name='$name', desc1='$desc1', desc2='$desc2', price='$price', image='$image'") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
I figured it out also thanks on the enctype i completely forgot about that. It works perfectly.
You need to add
enctype="multipart/form-data"
in the form so your form should be
<form action="specialadd.php" method="post" enctype="multipart/form-data">

Categories