Adding uploading to edit page - php

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

Related

Why do I can't get the title by using POST method?

So I am trying to get the title from the URL by using $_GET['title'] in the first PHP file, but I can't get the file on the 2nd file.
URL:
https://easy2book.000webhostapp.com/neworder.php?bookid=101&title=SENIOR%20secondary%20geography%20fieldwork%20and%20assessment%20practice%202021.%20For%20HKDSE%202021%20/%20Ip%20Kim%20Wai%20...%20[et%20al.].
1st File:
<?php
include_once 'header.php';
$id2 = mysqli_real_escape_string($conn, $_GET['bookid']);
$title2 = mysqli_real_escape_string($conn, $_GET['title']);
?>
<section class="neworder-form">
<h2>Order</h2>
<div class="neworder-form-form">
<form action="neworder.inc.php" method="post">
<table>
<tr>
<td>Book ID:</td>
<td>
<input type="text" disabled="disabled" name="bookid2" value="<?= $id2 ?>">
</td>
</tr>
<tr>
<td>Book Title: </td>
<td>
<input type="text" disabled="disabled" name="title2" value="<?= $title2 ?>">
</td>
</tr>
<tr>
<td>Username: </td>
<td>
<input type="text" name="uid2" placeholder="Username...">
</td>
</tr>
<tr>
<td>Comfirmed Book ID: </td>
<td>
<input type="text" name="id2" placeholder="Please enter the Book ID....">
</td>
</tr>
</table>
<button type="submit" name="submit2">Order</button>
</form>
</div>
<?php
// Error messages
if (isset($_GET["error"])) {
if ($_GET["error"] == "emptyinput2") {
echo "<p>Fill in all fields!</p>";
}
else if ($_GET["error"] == "usernametaken2") {
echo "<p>Username already taken!</p>";
}
}
?>
</section>
2nd File:
<?php
if (isset($_POST["submit2"])) {
// First we get the form data from the URL
$uid2 = $_POST["uid2"];
$id2 = $_POST["id2"];
$title2 = $_POST["title2"];
// Then we run a bunch of error handlers to catch any user mistakes we can (you can add more than I did)
// These functions can be found in functions.inc.php
require_once "dbh.inc.php";
require_once 'functions2.inc.php';
// Left inputs empty
// We set the functions "!== false" since "=== true" has a risk of giving us the wrong outcome
if (emptyInputOrder2($uid2,$id2) !== false) {
header("location: ../neworder.php?error=emptyinput&bookid=$id2&title=$title2");
exit();
}
// Is the username exists
if (uidExists2($conn, $uid2) !== true) {
header("location: ../neworder.php?error=undefineuser");
exit();
}
// If we get to here, it means there are no user errors
// Now we insert the user into the database
createUser($conn, $uid2, $id2);
} else {
header("location: ../neworder.php");
exit();
}
The input fields are disbled, disabled inputs are not posted.
Replace $title2 = $_POST[""]; with $title2 = $_POST["title2"];

updating table entry from edit button

Can anyone tell me where my problem is here, this page is linked from edit buttons I have embedded on a table of all entries. However, it is entering the current data into the fields and not updating when I enter new values? Any help appreciated.
php:
<?php
include_once("config.php");
date_default_timezone_set('Europe/London');
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$EditQuery = "SELECT * FROM ACW WHERE UserID=$id";
$results = sqlsrv_query ($conn, $EditQuery);
while($row = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC))
{
$firstname = $row['FirstName'];
$lastname = $row['LastName'];
$location = $row['location'];
}
if(isset($_POST['update']))
{
$id = $_POST['UserID'];
$firstname = $_POST['FirstName'];
$lastname = $_POST['LastName'];
$location = $_POST['location'];
// checking empty fields
if(empty($firstname) || empty($lastname) || empty($location)) {
if(empty($firstname)) {
echo "<font color='red'>First Name field is empty.</font><br/>";
}
if(empty($lastname)) {
echo "<font color='red'>Last Name field is empty.</font><br/>";
}
if(empty($location)) {
echo "<font color='red'>Location field is empty.</font><br/>";
}
//link to the previous page
echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";
}
if (preg_match("/^[0-9-]+$/",$firstname || $lastname || $location)) {
echo "<font color='red'>Numbers are not valid in these fields</font><br/>";
}
} else {
//updating the table
$UpdateQuery ="UPDATE ACW SET FirstName='$firstname', LastName='$lastname', location='$location' WHERE UserID='$id'";
echo $UpdateQuery;
//echo "<font color='green'>Data has been updated.</font><br/>";
$results = sqlsrv_query ($conn, $UpdateQuery);
}
?>
form:
<form name="form1" method="get" action="edit.php">
<table border="0">
<tr>
<td>First Name</td>
<td><input type="text" name="firstname" value="<?php echo $firstname;?>"></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastname" value="<?php echo $lastname;?>"></td>
</tr>
<tr>
<td>Location</td>
<td><input type="text" name="location" value="<?php echo $location;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
I suggest you make 3 changes:
1.0 Give the form inputs different variable names to the one collected from the database( e.g instead of $firstname give but say $firstname_form)
2.0 Your form has method as GET but you are using POST to update
3.0 Your form action page is edit.php but the fact that you are collecting the item id via GET means that your edit button must be linked to a certain edit.php?id=$item_id Hence the action page should be edit.php?id=$id
c/o your comment: Yes. Exactly what I imagined. So, for your form action replace edit.php with edit.php?id=<?php if(isset($id)){ echo $id; } ?> You are saying that, if the id exist on this page display it as paramater.
I wasn't asking for your link button to be changed. It is correct. To prove that it is correct, echo the id at your edit page like this
if(isset($_GET['id'])){
$id = $_GET['id'];
echo $id;
exit();
}
You can then comment or remove the echo and exit lines after confirming that the id is passed to the edit page.
Now, on your form I was saying that the action should look like this
<form action="edit.php?id=<?php if(isset($id)){ echo $id; } ?>" method="GET" name="form1">
</form>
Adjust the variable names as I suggested earlier as well as changing input verification from POST to GET. Your database should now be updated.

EDIT php file only displays error

I have made a edit.php file .It seems to work but it only displays error from the echo line (end of the line). I can't seem to find where i have mistyped or have not typed in the coding.
What should I do to fix this?
<?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($songid, $title, $artist, $genre, $lyrics, $language, $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>
<?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">
<input type="hidden" name="songid" value="<?php echo $songid; ?>"/>
<table style="margin-left:auto; margin-right:auto; width:400px;">
<tbody>
<tr style="text-align:center">
<td colspan="2"><h2 style="color:#00008b;">Edit song into Music Database</h2><label style="color:#FF0000;"></label></td>
</tr>
<tr>
<td>Title<label style="color:#FF0000;"></label></td>
<td><input type="text" name="title"></td>
</tr>
<tr>
<td>Artist<label style="color:#FF0000;"></label></td>
<td><input type="text" name="artist"></td>
</tr>
<tr>
<td>Genre<label style="color:#FF0000;"></label></td>
<td><input type="text" name="genre"></td>
</tr>
<tr>
<td>Language<label style="#FF0000;"></label></td>
<td><input type="text" name="language"></td>
</tr>
<tr>
<td>Lyrics: <label style="#FF0000;"></label></td>
<td><textarea name="lyrics" rows="5" cols="50"></textarea></td>
</tr>
<tr style="text-align:center">
<td colspan="2"><input type="submit" name="submit" value="Submit"></td>
</tr>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
<?php
} // continue end of function of renderform
// connect to the database
include('connect-db.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['songid']))
{
// get form data, making sure it is valid
$songid = (isset($_POST['songid']) ? $_POST['songid'] : null);
$title = (isset($_POST['title']) ? $_POST['title'] : null);
$artist = (isset($_POST['artist']) ? $_POST['artist'] : null);
$genre = (isset($_POST['genre']) ? $_POST['genre'] : null);
$lyrics = (isset($_POST['lyrics']) ? $_POST['lyrics'] : null);
$language = (isset($_POST['language']) ? $_POST['language'] : null);
// check that firstname/lastname fields are both filled in
if ($title == '' || $artist == '' || $genre == '' || $lyrics == '' || $language == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($songid, $title, $artist, $genre, $lyrics, $language, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE players SET title='$title', artist='$artist', genre='$genre', lyrics='$lyrics', language='$language' WHERE songid='$songid'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.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 'songid' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['songid']) && is_numeric($_GET['songid']) && $_GET['songid'] > 0)
{
// query db
$songid = $_GET['songid'];
$result = mysql_query("SELECT * FROM songs WHERE songid=$songid")
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
$title = $row['title'];
$artist = $row['artist'];
$genre = $row['genre'];
$lyrics = $row['lyrics'];
$language= $row['language'];
// show form
renderForm($songid, $title, $artist, $genre, $lyrics, $language, $error);
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'songid' in the URL isn't valid, or if there is no 'songid' value, display an error
{
echo 'Error!';
}
}
?>
According to your first screenshot, you use id in the URL instead of songid.
Try changing id to songid, like localhost/songdb/edit.php?songid=14
Propably you defined function but not executed. Please check it:
<?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
renderForm();
function renderForm($songid, $title, $artist, $genre, $lyrics, $language, $error)
{...}
your code has some syntax errors but I fixed it also something to note is I tidied up your code and move some stuff around also noticed you were using MySQL when it is deprecated so I made it MySQLI and I gave you the way to connect to your database also when changing header location it is suggested that you put exit(); afterwards to stop the rest of the PHP code from running
<?php
include('connect-db.php');
function renderForm($songid, $title, $artist, $genre, $lyrics, $language, $error){
}
if (isset($_POST['submit'])){
if (is_numeric($_POST['songid'])){
$songid = (isset($_POST['songid']) ? $_POST['songid'] : null);
$title = (isset($_POST['title']) ? $_POST['title'] : null);
$artist = (isset($_POST['artist']) ? $_POST['artist'] : null);
$genre = (isset($_POST['genre']) ? $_POST['genre'] : null);
$lyrics = (isset($_POST['lyrics']) ? $_POST['lyrics'] : null);
$language = (isset($_POST['language']) ? $_POST['language'] : null);
if ($title == null || $artist == null || $genre == null || $lyrics == null || $language == null){
$error = 'ERROR: Please fill in all required fields!';
} else {
$conn = new mysqli('host', 'username', 'password', 'DB');// This will be located in your connect.php but the refrence variable("$conn") is important if you are going to use this php
$conn->query("UPDATE players SET '$title', artist='$artist', genre='$genre', lyrics='$lyrics', language='$language' WHERE songid='$songid''");
header("Location: view.php");
exit();
}
} else {
$error = "Song Id is not valid";
}
}
if (isset($_GET['songid']) && is_numeric($_GET['songid']) && $_GET['songid'] > 0){
$songid = $_GET['songid'];
"SELECT * FROM songs WHERE songid=$songid"
$result = $conn->query("UPDATE players SET '$title', artist='$artist', genre='$genre', lyrics='$lyrics', language='$language' WHERE songid='$songid''");
$row = $result->fetch_assoc();
if(mysqli_num_rows($result) > 0){
$title = $row['title'];
$artist = $row['artist'];
$genre = $row['genre'];
$lyrics = $row['lyrics'];
$language= $row['language'];
renderForm($songid, $title, $artist, $genre, $lyrics, $language, $error); // Still not quite sure what you are doing with this function because there is no function made on this current php script
} else {
$error = "No results!";
}
} else {
$error = "Song id in URL is not valid";
}
?>
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<?php
if ($error){
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="songid" value="<?php echo $songid; ?>"/>
<table style="margin-left:auto; margin-right:auto; width:400px;">
<tbody>
<tr style="text-align:center">
<td colspan="2"><h2 style="color:#00008b;">Edit song into Music Database</h2><label style="color:#FF0000;"></label></td>
</tr>
<tr>
<td>Title<label style="color:#FF0000;"></label></td>
<td><input type="text" name="title"></td>
</tr>
<tr>
<td>Artist<label style="color:#FF0000;"></label></td>
<td><input type="text" name="artist"></td>
</tr>
<tr>
<td>Genre<label style="color:#FF0000;"></label></td>
<td><input type="text" name="genre"></td>
</tr>
<tr>
<td>Language<label style="#FF0000;"></label></td>
<td><input type="text" name="language"></td>
</tr>
<tr>
<td>Lyrics: <label style="#FF0000;"></label></td>
<td><textarea name="lyrics" rows="5" cols="50"></textarea></td>
</tr>
<tr style="text-align:center">
<td colspan="2"><input type="submit" name="submit" value="Submit"></td>
</tr>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

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.

How to call php function from html form action?

I want to call php function in form action and i want to pass id as a argument. What I am doing is, in html form database column values will be displayed in text boxes, If I edit those values and click 'update' button values in database should be updated and 'Record updated successfully'message should be displayed in same page. I tried below code but not working. Let me know the solution. Thanks in advance.
<html>
<head>
<link rel="stylesheet" type="text/css" href="cms_style.css">
</head>
<?php
$ResumeID = $_GET['id'];
$con = mysql_connect("localhost", "root", "");
mysql_select_db("engg",$con);
$sql="SELECT * from data WHERE ResumeID=$ResumeID";
$result = mysql_query($sql);
$Row=mysql_fetch_row($result);
function updateRecord()
{
//If(!isset($_GET['id']))
//{
$NameoftheCandidate=$_POST[NameoftheCandidate];
$TelephoneNo=$_POST[TelephoneNo];
$Email=$_POST[Email];
$sql="UPDATE data SET NameoftheCandidate='$_POST[NameoftheCandidate]', TelephoneNo='$_POST[TelephoneNo]', Email='$_POST[Email]' WHERE ResumeID=$ResumeID ";
if(mysql_query($sql))
echo "<p>Record updated Successfully</p>";
else
echo "<p>Record update failed</p>";
while ($Row=mysql_fetch_array($result)) {
echo ("<td>$Row[ResumeID]</td>");
echo ("<td>$Row[NameoftheCandidate]</td>");
echo ("<td>$Row[TelephoneNo]</td>");
echo ("<td>$Row[Email]</td>");
} // end of while
} // end of update function
?>
<body>
<h2 align="center">Update the Record</h2>
<form align="center" action="updateRecord()" method="post">
<table align="center">
<input type="hidden" name="resumeid" value="<? echo "$Row[1]"?>">
<? echo "<tr> <td> Resume ID </td> <td>$Row[1]</td> </tr>" ?>
<div align="center">
<tr>
<td> Name of the Candidate</td>
<td><input type="text" name="NameoftheCandidate"
size="25" value="<? echo "$Row[0]"? >"></td>
</tr>
<tr>
<td>TelephoneNo</td>
<td><input type="text" name="TelephoneNo" size="25" value="<? echo "$Row[1]"?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="Email" size="25" value="<? echo "$Row[3]"?>">
</td>
</tr>
<tr>
<td></td>
<td align="center"><input type="submit" name="submitvalue" value="UPDATE" ></td>
</tr>
</div>
</table>
</form>
</body>
</html>
try this way
HTML
<form align="center" action="yourpage.php?func_name=updateRecord" method="post">
PHP
$form_action_func = $_POST['func_name'];
if (function_exists($form_action_func)) {
updateRecord();
}
write form action="" and then write your php code as below
note : use form method as get
<?php
if(isset($_GET['id']))
{
call your function here
}
?>
in function access all values using $_GET['fieldname']
simple way make your "Submit " and "Update" action performed on same page then
if(isset($_POST['update']))
{
//perform update task
update($var1,var2,$etc); // pass variables to function
header('Location: http://www.example.com/');// link to your form
}
else if(isset($_POST['submit']))
{
//perform update task
submit($var1,$var2,$etc);// pass variables to function
header('Location: http://www.example.com/'); // link to next page after submit successfully
}
else
{
// display form
}

Categories