file upload (php) two warnings - php

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");
}
?>

Related

How to update old image if no image selected in php

I can all input type values view in my update page but, I can't display file input value for ex: photo. Here I can be displayed image location value in a separate part.
My problem for
When I update the only name or mother name or anyone without photo all fields values update correctly but my image is updated empty values. when I update with a photo and other details then only my photo updated correctly. so help me how to update photo values with edit without edit.....
update.php
<!doctype html>
<html>
<body>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$upd = $_GET['upd'];
mysql_connect('localhost','root','');
mysql_select_db("display");
$slc = "SELECT * from photos WHERE firstname = '$upd'";
$run = mysql_query($slc);
while($row=mysql_fetch_array($run)){
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$location=$row['location'];
}
?>
<div class="update">
<table align="center" border="">
<tr>
<td colspan="4"><center><h1 style="color:red">Student Form Updation</h1>
</center></td></tr>
<form method="post" enctype="multipart/form-data" action="update.php?upd=<?
php echo $firstname; ?> "/>
<tr><td><label>First Name:</label></td><td>
<input type="text" name="firstname" value="<?php echo $firstname ?> " />
</td>
<td><label>Last Name:</label></td><td>
<input type="text"name="lastname" value="<?php echo $lastname?>" /></td>
</tr>
<td><label>Select Photo</label></td>
<td> <input type="file" name="image" class="ed" id="location" value= "<?php
echo $location?>"/> <?php echo '<img width="100px" height="100px"
src="'.$location.'">'; ?>
</td>
</tr>
<tr><td></td><td><input type="submit" name="update" value="Update"
id="button1" /></td>
<td><input type="submit" formaction="errview.php" value="View" id="button1"
/></td><td></td></tr>
</form>
</div>
<?php
if(isset($_POST['update']))
{
$nid = $_GET['upd'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$file=$_FILES['image']['tmp_name'];
$image=addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"photos/" . $_FILES["image"]
["name"]);
$location="photos/" . $_FILES["image"]["name"];
$update = "UPDATE photos SET firstname='$firstname', lastname =
'$lastname',location='$location' WHERE firstname='$nid'";
$run = mysql_query($update);
echo "<script>alert('Update SuccessFull!');location.href='update.php?
upd=$firstname'</script>";
}
?>
</body>
</html>
You Can Modify Your Update Code Like This:
If no image is selected It will not Update Your Image in Database It Will Only Update Your Image in the database if an image is selected
<?php
if (isset($_POST['update'])) {
$nid = $_GET['upd'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$file = $_FILES['image']['tmp_name'];
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"], "photos/" . $_FILES["image"]["name"]);
$location = "photos/" . $_FILES["image"]["name"];
if ((!($_FILES['image']['name']))) /* If there Is No file Selected*/ {
$update = "UPDATE photos SET firstname='$firstname', lastname =
'$lastname' WHERE firstname='$nid'";
} else /* If file is Selected*/ {
$update = "UPDATE photos SET firstname='$firstname', lastname =
'$lastname',location='$location' WHERE firstname='$nid'";
}
$run = mysql_query($update);
echo "<script>alert('Update SuccessFull!');location.href='update.php?
upd=$firstname'</script>";
}
?>
<?php
if(empty($image)){
$product_img1=$row_edit['image'];
}
else{
$temp_name1=$_FILES['product_img1']['tmp_name'];
move_uploaded_file($temp_name1,"product_images/$product_img1");
}
?>

Why unlink function will not delete old image when uploading image

I have to manually go into my folder every time I update an image. The image will update to a new image. However, when I update an image, the old image is not being deleted. I am using the PHP function unlink to delete the image but for some reason its not working. I have removed the at "#" sign from php unlink in the code. I have re-edited coded the code. I keep getting the following error:
Warning: unlink(picture/): Permission denied in C:\xampp\htdocs\upload_update\New_project\edit_image.php on line 24
I am trying to teach myself php, Thank you so much for your help.
This is the code:
<?php
include "connection.php";
$vid="";
$vname="";
$vprice="";
$vpicture="";
if(isset($_POST["button_edit"])){
$product_name = $_POST["product_name"];
$product_price = $_POST["product_price"];
$product_id = $_POST["product_id"];
$old_picture = $_POST['old_picture'];
if(!empty($_FILES["product_picture"]["name"])) {
$product_picture = $_FILES["product_picture"]["name"];
$qry = mysqli_query($con,"Update table_product Set product_name='$product_name', product_price='$product_price', product_picture='$product_picture' Where product_id='$product_id'");
$target_dir = "picture/";
$target_file = $target_dir . basename($_FILES["product_picture"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES["product_picture"]["tmp_name"],$target_file);
if (isset($old_picture) && ($old_picture != $product_picture)) {
unlink("picture/" . $old_picture);
}
}
else{
$qry = "Update table_product Set product_name='$product_name', product_price='$product_price' Where product_id='$product_id'";
}
$qryUpdate = mysqli_query($con,$qry);
}
else if(isset($_GET["edit"])){
$qry = mysqli_query($con,"Select * From table_product Where product_id='".$_GET["edit"]."'");
while($row=mysqli_fetch_array($qry,MYSQLI_ASSOC)){
$vid=$row["product_id"];
$vname=$row["product_name"];
$vprice=$row["product_price"];
$vpicture=$row["product_picture"];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Product</title>
</head>
<body>
<form action='<?php echo $_SERVER["PHP_SELF"]; ?>' method="post" enctype="multipart/form-data" >
<table>
<tr>
<td>Product ID</td>
<td><input type="text" name="product_id" value="<?php echo $vid;?>"></td></tr>
<tr><td>Product Name</td>
<td><input type="text" name="product_name" value="<?php echo $vname;?>"></td></tr>
<tr><td>Product Price</td>
<td><input type="text" name="product_price" value="<?php echo $vprice;?>"></td></tr>
<input type="hidden" name="old_picture" value="<?php if (!empty($old_picture)) echo $old_picture; ?>" />
<tr><td>Product Picture</td>
<td><input type="file" name="product_picture" ></td></tr>
<?php if (!empty($old_picture)) {
echo '<img class="profile" src="picture/' . $old_picture . '" alt="image" style=width:150px;height:xpx;">';
} ?>
<tr><td colspan="2">
<input type="submit" name="button_add" value="Add">
<input type="submit" name="button_edit" value="Edit"></td></tr> </table>
</form>
<table border=1>
<tr><th>product ID</th><th>product Name</th>
<th>product price</th><th>product image</th> <th>Action</th></tr>
<?php
$qry =mysqli_query($con, "Select * From table_product");
while($row=mysqli_fetch_array($qry,MYSQLI_ASSOC)){
echo '<tr><td>'.$row["product_id"].'</td>';
echo '<td>'.$row["product_name"].'</td>';
echo '<td>'.$row["product_price"].'</td>';
echo '<td><img src="picture/'.$row["product_picture"].'" style=width:100px;height:xpx;"/></td>';
echo '<td>Edit </td></tr>';
}
?>
</table>
<br><br><br>
</body>
</html>
remove # sign from this line:
#unlink("picture/".$_GET["picture"])
this may show you warnings.
Use absolute path to file you want to unlink, not relative so your unlink should look like that
#unlink(__DIR__."/picture/".$_GET["picture"]);

Updating an image and text at the same time in Php and Mysql

Users can add, edit and delete content on my web page. People can edit the text and the image they upload. However, the image will not display if I only edit the text. When I edit the text but not the image, a white box is displayed where the image should appear. On the other hand, the image will appear if I only edit the photo but nothing else. Only the text will update when I try to edit both the image and text together.I want the user to be able to edit their text and image like they can on a profile page. Once the text and the image is edited, I want the old image to be deleted out of the folder. How can I edit the image and the text together? I am not getting any errors. Please help, I'm new to Php and MySQL. Thank you for your time. This is the code:
<?php
include "connection.php";
$vid="";
$vname="";
$vprice="";
if(isset($_POST["button_add"])){
$product_name = $_POST["product_name"];
$product_price = $_POST["product_price"];
$product_picture = $_FILES["product_picture"]["name"];
$qry = mysqli_query($con, "INSERT INTO table_product values('','$product_name','$product_price','$product_picture')") or die("Can not query database" );
if($qry){
$target_dir = "picture/";
$target_file = $target_dir . basename($_FILES["product_picture"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(move_uploaded_file($_FILES["product_picture"]["tmp_name"],
$target_file)){
echo"file uploaded";
}
else{
echo "Upload fail";
}
}
}
else if(isset($_POST["button_edit"])){
$product_name = $_POST["product_name"];
$product_price = $_POST["product_price"];
$product_id = $_POST["product_id"];
if(isset($_FILES["product_picture"]["name"])){
$product_picture = $_FILES["product_picture"]["name"];
$qry = mysqli_query($con,"Update table_product Set product_name='$product_name', product_price='$product_price', product_picture='$product_picture' Where product_id='$product_id'");
$target_dir = "picture/";
$target_file = $target_dir . basename($_FILES["product_picture"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES["product_picture"]["tmp_name"],$target_file);
}
else{
$qry = "Update table_product Set product_name='$product_name', product_price='$product_price' Where product_id='$product_id'";
}
$qry_update = mysqli_query($con,$qry);
}
if(isset($_GET["delete"])){
$qry = mysqli_query($con, "Delete From table_product Where product_id='".$_GET["delete"]."'" );
if($qry){
#unlink("picture/".$_GET["picture"]);
}
}
else if(isset($_GET["edit"])){
$qry = mysqli_query($con,"Select * From table_product Where product_id='".$_GET["edit"]."'");
while($row=mysqli_fetch_array($qry,MYSQLI_ASSOC)){
$vid=$row["product_id"];
$vname=$row["product_name"];
$vprice=$row["product_price"];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Product</title>
</head>
<body>
<form action='<?php echo $_SERVER["PHP_SELF"]; ?>' method="post" enctype="multipart/form-data" >
<table>
<tr>
<td>Product ID</td>
<td><input type="text" name="product_id" value="<?php echo $vid;?>"></td></tr>
<tr><td>Product Name</td>
<td><input type="text" name="product_name" value="<?php echo $vname;?>"></td></tr>
<tr><td>Product Price</td>
<td><input type="text" name="product_price" value="<?php echo $vprice;?>"></td></tr>
<tr><td>Product Picture</td>
<td><input type="file" name="product_picture"></td></tr>
<tr><td colspan="2">
<input type="submit" name="button_add" value="Add">
<input type="submit" name="button_edit" value="Edit"></td></tr> </table>
</form>
<table border=1>
<tr><th>product ID</th><th>product Name</th>
<th>product price</th><th>product image</th> <th>Action</th></tr>
<?php
$qry =mysqli_query($con, "Select * From table_product");
while($row=mysqli_fetch_array($qry,MYSQLI_ASSOC)){
echo '<tr><td>'.$row["product_id"].'</td>';
echo '<td>'.$row["product_name"].'</td>';
echo '<td>'.$row["product_price"].'</td>';
echo '<td><img src="picture/'.$row["product_picture"].'" style=width:100px;height:xpx;"/></td>';
echo '<td>Edit |Delete</td></tr>';
}
?>
</table>
<br><br><br>
</body>
</html>
What is happening is when you edit only the text, the query called also updates the image path but since you don`t add an image it will be NULL.
One way is to build a conditional query inside the edit click
if(isset($_FILES["product_picture"]["name"]))
{
$product_picture = $_FILES["product_picture"]["name"];
$sql = "Update table_product Set product_name='$product_name', product_price='$product_price', product_picture='$product_picture' Where product_id='$product_id'";
target_dir = "picture/";
$target_file = $target_dir . basename($_FILES["product_picture"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES["product_picture"]["tmp_name"],$target_file);
}
else{
$sql = "Update table_product Set product_name='$product_name', product_price='$product_price' Where product_id='$product_id'"
}
qry = mysqli_query($con,$sql);

Error : Undefined index: image for ($_FILES['image']['name']) [duplicate]

This question already has answers here:
What does enctype='multipart/form-data' mean?
(9 answers)
Closed 6 years ago.
I have a simple registration form, in which I accept inputs from the user that includes an image, and insert the values in a table : temporary_employees table . In my code, I check whether the email id and the user id entered by the user already exists and if they dont , i go ahead and perform the insert after moving the image to a folder named 'images' . While running the code , I am getting an error Undefined index: image, on the line where I have the following piece of code :
$target_file = $target_path . basename ($_FILES['image']['name']);
The most interesting thing is the same line of code has worked perfectly well in another php file . I had given the same name for the input in the html form . . How is it possible ? Any help will be appreciated .
Here is my code :
//start the session before anything is echoed to the browser
if (session_status()===PHP_SESSION_NONE) {
session_start();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>
Login form
</title>
</head>
<body>
<h3>Registration Form</h3>
<form action ="" method="POST">
<table align="center" cellpadding="10">
<tr>
<td>Name</td>
<td><input type="text" maxlength='100' name="empname" id="empname" required></td>
</tr>
<tr>
<td>Email Id</td>
<td><input type="text" maxlength='100' name="emailid" id="emailid" required>
</td>
</tr>
<tr>
<td>User Id</td>
<td><input type="text" maxlength='100' name="userid" id="userid" required ></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" maxlength='100' name="pwd" id="pwd" required ></td>
</tr>
<tr>
<td>Date of Birth</td>
<td>
<select name='year'>
<option value='2015'>2015</option>
<option value='2016'>2016</option>
</select>
<select name='month'>
<option value='01'>January</option>
<option value='02'>February</option>
<option value='03'>March</option>
<option value='04'>April</option>
<option value='05'>May</option>
</select>
<select name='day'>
<option value='01'>1</option>
<option value='02'>2</option>
<option value='03'>3</option>
<option value='04'>4</option>
<option value='05'>5</option>
</select></td>
</tr>
<tr>
<td>Designation</td>
<td><input type="text" maxlength='100' name="designation" id="designation" required></td>
</tr>
<tr>
<td>Department</td>
<td><input type="text" maxlength='100' name="department" id="department" required></td>
</tr>
<tr>
<td>Image</td>
<td><input type="file" maxlength='100' name="image" required></td>
</tr>
<tr>
<td>
<input type="submit" name="login" value="Register Yourself">
</td>
</tr>
</table>
</form>
</body>
</html>
<?php
//create a connection
$conn = mysqli_connect('localhost', 'root', '', 'attendance');
//on the click of submit button
if (isset($_POST['login'])) {
//capture the $_POST values
$name = $_POST['empname'];
$name = trim($name);
$email = $_POST['emailid'];
$email = trim($email);
$userid = $_POST['userid'];
$userid = trim($userid);
$pwd = $_POST['pwd'];
$pwd = trim($pwd);
$desg = $_POST['designation'];
$desg = trim($desg);
$dept = $_POST['department'];
$dept = trim($dept);
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$date = $year.$month.$day;
//display a message if there is a blank entry for email
if ($email=="") {
echo "Please enter a valid email id";
}
//display a message if there is a blank entry for userid
if ($userid=="") {
echo "Please enter a valid User Id";
}
//check if the email id exists
$sql_check_email = "select * from employee where emp_email='$email';";
mysqli_query($conn, $sql_check_email);
$aff_email = mysqli_affected_rows($conn);
// if email id exists ..display message
if ($aff_email==1) {
$msgemail = "The email id exists";
echo $msgemail;
//display error message if there is an error
} else if ($aff_email>1) {
$msgemail = "There are multiple employees with the same email";
echo $msgemail;
//display message if there is an error firing the query
} else if ($aff_email<0) {
echo "There is an error ..Try again";
}
//check if the user id exists
$sql_check_userid = "select * from employee_login where emp_uid='$userid';";
mysqli_query($conn, $sql_check_userid);
$aff_userid = mysqli_affected_rows($conn);
if ($aff_userid==1) {
$umsg = "User id already exist";
echo $umsg;
//display error message if there is an error when the query is fired
} else if ($aff_userid<0) {
echo "There is an error ..Try again";
}
//if neither the user id nor the email id exist, upload image and do the insert
if ($aff_userid==0 && $aff_email==0) {
$target_path = "images/";
$target_file = $target_path . basename ($_FILES['image']['name']);
//if the image is moved to the images folder , do the insert
if (move_uploaded_file($_FILES['image']['tmp_name'], $target_file)) {
$image = basename($_FILES['image']['name']);
$sql_ins = "INSERT INTO temporary_employee(emp_uid,emp_pwd,
emp_name,emp_email,emp_dob,emp_designation,
emp_department,emp_image)
VALUES('$userid','$pwd','$name','$email','$date',
'$desg','$dept','$image')";
mysqli_query($conn, $sql_ins);
$aff_insert = mysqli_affected_rows($conn);
//display success message if insert is successfull
if ($aff_insert==1) {
echo "You have successfully registered ...awaiting approval by admin";
//display message if there were no insert
} else if ($aff_insert==0) {
echo "The registration has failed ..Try again";
//diplay error message if there was an error while firing the insert query
} else if ($aff_insert<0) {
echo "There was an error ..Try again";
}
}
}
}
?>
While using Image Uploading in the form you have to use the enctype in the form attribute.
<form action ="" method="POST" enctype="multipart/form-data">
</form>
Change
<form action ="" method="POST">
to
<form enctype="multipart/form-data">
And try again.
The enctype attribute specifies how the form-data should be encoded when submitting it to the server.

Adding uploading to edit page

I have been trying the whole week to get this too work but haven't had any luck thus far. I am building an employee system, being my first project I could really use your help.
I have a database with a table called ref_employees with x amount of fields.
I managed to get my hands on some source to edit the record and thought that my problem was solved. Although the source helped me to edit the records, the client needs more functionality by means of upload and storing functionality. I have edited the code accordingly but have 2 issues now.
1) I had to add the upload form separate to the editing form because when the edits' update is clicked it clears the upload fields within the db even after adding echoing out the current values within the upload fields in the db.
2) The uploads shows that it is uploading but is doesn't get saved in the specified directory. The permissions are set to 777, and the file names are not captured in the database in the relevant fields. I think it is because the upload function is in a separate page and not on the same page as the upload form.
I need it to upload the file, store it in a directory and finally place the file name in the db where the warning fields are, but it needs to be captured under the record (employee) being edited.
I am new to this and all help is appreciated.
The edit page:
<?php
include 'core/init.php';
protect_page();
include 'includes/overall/header.php';
error_reporting(1);
?>
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($idnumber, $firstname, $lastname, $department, $manager, $startdate, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<div class="article">
<h1>Employee Details</h1>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="idnumber" value="<?php echo $idnumber; ?>"/>
<div>
<p>* Required</p>
<p><strong>ID:</strong> <?php echo $idnumber; ?></p>
<table cellpadding="5" cellspacing="5">
<tr>
<td><strong>First Name: *</strong></td>
<td><input type="text" name="firstname" value="<?php echo $firstname; ?>"/></td>
</tr>
<tr>
<td><strong>Last Name: *</strong></td>
<td> <input type="text" name="lastname" value="<?php echo $lastname; ?>"/></td>
</tr>
<tr>
<td><strong>Department: *</strong> </td>
<td> <input type="text" name="department" value="<?php echo $department; ?>"/></td>
</tr>
<tr>
<td><strong>Manager/Superviser: *</strong></td>
<td><input type="text" name="manager" value="<?php echo $manager; ?>"/></td>
</tr>
<tr>
<td><strong>Start Date: *</strong></td>
<td><input type="text" name="startdate" value="<?php echo $startdate; ?>"/></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit" class="btn"></td>
</tr>
</table>
</form>
<tr>
<td>
<table cellpadding="5" cellspacing="0">
<form action="includes/add.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="idnumber" value="<?php echo $idnumber; ?>"/>
<th>Ad Warnings Documents</th>
<tr>
<td>Warning File 1</td>
<td><input type="file" name="warning1" value="<?php echo $warning1;?>" /></td>
</tr>
<tr>
<td>Warning File 2</td>
<td><input type="file" name="warning2" value="<?php echo $warning2;?>" /></td>
</tr>
<tr>
<td>Warning File 3</td>
<td><input type="file" name="warning3" value="<?php echo $warning3;?>" /></td>
</tr>
<tr><td><input type="submit" name="submit" value="upload"></td></tr>
</table>
</td>
<td></td>
</tr>
</table>
</div>
</body>
</html>
<?php
}
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['idnumber']))
{
// get form data, making sure it is valid
$idnumber = $_POST['idnumber'];
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$lastname = mysql_real_escape_string(htmlspecialchars($_POST['lastname']));
$department = mysql_real_escape_string(htmlspecialchars($_POST['department']));
$manager = mysql_real_escape_string(htmlspecialchars($_POST['manager']));
$startdate = mysql_real_escape_string(htmlspecialchars($_POST['startdate']));
// check that firstname/lastname fields are both filled in
if ($firstname == '' || $lastname == '')
{
// generate error message
$error = 'ERROR: Please fill in all fields!';
//error, display form
renderForm($idnumber, $firstname, $lastname, $department, $manager, $startdate, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE ref_employees SET firstname='$firstname', lastname='$lastname', department='$department', manager='$manager', startdate='$startdate' WHERE idnumber='$idnumber'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: employeelist.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['idnumber']) && is_numeric($_GET['idnumber']) && $_GET['idnumber'] > 0)
{
// query db
$idnumber = $_GET['idnumber'];
$result = mysql_query("SELECT * FROM ref_employees WHERE idnumber=$idnumber")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$department = $row['department'];
$manager = $row['manager'];
$startdate = $row['startdate'];
$warning1 = $row['warning1'];
$warning2 = $row['warning2'];
$warning3 = $row['warning3'];
// show form
renderForm($idnumber, $firstname, $lastname, $department, $manager, $startdate, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
<h1>Additional options</h1>
</div>
The file upload source file add.php
<?php
include 'core/init.php';
protect_page();
include 'includes/overall/header.php';
error_reporting(1);
?>
<?php
//This is the directory where images will be saved
$target = "files/empdocs";
$target1 = $target . basename( $_FILES['warning1']['name']);
$target2 = $target . basename( $_FILES['warning2']['name']);
$target3 = $target . basename( $_FILES['warning3']['name']);
//This gets all the other information from the form
$warning1=($_FILES['warning1']['name']);
$warning2=($_FILES['warning2']['name']);
$warning3=($_FILES['warning3']['name']);
//Writes the information to the database
mysql_query("INSERT INTO ref_employees VALUES ('$warning1', '$warning2', '$warning3')") ;
//Writes the file to the server
if (move_uploaded_file($_FILES['warning1']['tmp_name'], $target1)
&& move_uploaded_file($_FILES['warning2']['tmp_name'], $target2)
&& move_uploaded_file($_FILES['warning3']['tmp_name'], $target3)) {
//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.";
}
?>

Categories