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.
Related
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"];
I'm pretty new to coding with php and SQL, so I'm probably going to have a lot of questions. But as the title states, I'm getting this error...
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
I'm not sure what this is referring to. I've gone over the code as much as I can, but I can't find a syntax error. Maybe it's something I just don't know yet.
<?php
// including the database connection file
include_once("config.php");
if(isset($_POST['update']) && isset($_GET['site']))
{
$sitenumber = $_POST['sitenumber'];
$videolink = $_POST['videolink'];
$daynight = $_POST['daynight'];
$maxtents = $_POST['maxtents'];
$maxpersons = $_POST['maxpersons'];
$geography = $_POST['geography'];
$view = $_POST['view'];
$forestcover = $_POST['forestcover'];
$waterfront = $_POST['waterfront'];
$firepit = $_POST['firepit'];
$description = $_POST['description'];
$reslink = $_POST['reslink'];
// checking empty fields
if(empty($sitenumber) || empty($videolink) || empty($daynight) ||
empty($maxtents) || empty($maxpersons) || empty($geography) ||
empty($view) || empty($forestcover) || empty($waterfront) ||
empty($firepit) || empty($description) || empty($reslink)) {
if(empty($sitenumber)) {
echo "<font color='red'>Site Number field is empty.</font><br/>";
}
if(empty($videolink)) {
echo "<font color='red'>YouTube Link field is empty.</font><br/>";
}
if(empty($daynight)) {
echo "<font color='red'>Day or overnight field is empty.</font>
<br/>";
}
if(empty($maxtents)) {
echo "<font color='red'>Maximum Tents field is empty.</font><br/>";
}
if(empty($maxpersons)) {
echo "<font color='red'>Maximum Persons field is empty.</font>
<br/>";
}
if(empty($geography)) {
echo "<font color='red'>Geography field is empty.</font><br/>";
}
if(empty($view)) {
echo "<font color='red'>View field is empty.</font><br/>";
}
if(empty($forestcover)) {
echo "<font color='red'>Forest Cover field is empty.</font><br/>";
}
if(empty($waterfront)) {
echo "<font color='red'>Waterfront Access field is empty.</font>
<br/>";
}
if(empty($firepit)) {
echo "<font color='red'>Firepit field is empty.</font><br/>";
}
if(empty($description)) {
echo "<font color='red'>Description field is empty.</font><br/>";
}
if(empty($reslink)) {
echo "<font color='red'>Reservation Link Access field is empty.
</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE sites SET
sitenumber='$sitenumber',videolink='$videolink',daynight='$daynight',
maxtents='$maxtents',maxpersons='$maxpersons',geography='$geography',
view='$view',forestcover='$forestcover',waterfront='$waterfront',
firepit='$firepit',description='$description',reslink='$reslink' WHERE
sitenumber=$sitenumber");
//redirectig to the display page. In our case, it is index.php
//header("Location: index.php");
}
}
echo mysqli_error($mysqli);
?>
<?php
//getting id from url
$sitenumber = $_GET['site'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM sites WHERE
sitenumber=$sitenumber");
while($res = mysqli_fetch_array($result))
{
$sitenumber = $res['sitenumber'];
$videolink = $res['videolink'];
$daynight = $res['daynight'];
$maxtents = $res['maxtents'];
$maxpersons = $res['maxpersons'];
$geography = $res['geography'];
$view = $res['view'];
$forestcover = $res['forestcover'];
$waterfront = $res['waterfront'];
$firepit = $res['firepit'];
$description = $res['description'];
$reslink = $res['reslink'];
}
echo mysqli_error($mysqli);
?>
<html>
<head>
<title>Edit Data</title>
</head>
<body>
Home
<br/><br/>
<form name="form1" method="post" action="edit.php">
<table border="0">
<tr>
<td>Site Number</td>
<td><input type="number" name="sitenumber" value="<?php echo
$sitenumber;?>"></td>
</tr>
<tr>
<td>YouTube Link</td>
<td><input type="url" name="videolink" value="<?php echo
$videolink;?>"></td>
</tr>
<tr>
<td>Day or Overnight</td>
<td><select name="daynight" value="<?php echo $daynight;?>">
<option value="Day">Day</option>
<option value="Overnight">Overnight</option></td>
</tr>
<tr>
<td>Maximum Tents</td>
<td><input type="number" name="maxtents" value="<?php echo
$maxtents;?>"></td>
</tr>
<tr>
<td>Maximum Persons</td>
<td><input type="number" name="maxpersons" value="<?php echo
$maxpersons;?>"></td>
</tr>
<tr>
<td>Geography</td>
<td><input type="text" name="geography" value="<?php echo
$geography;?>"></td>
</tr>
<tr>
<td>View</td>
<td><input type="text" name="view" value="<?php echo $view;?>">
</td>
</tr>
<tr>
<td>Forest Cover</td>
<td><input type="text" name="forestcover" value="<?php echo
$forestcover;?>"></td>
</tr
<tr>
<td>Waterfront Access</td>
<td><select name="waterfront" value="<?php echo $waterfront;?>">
<option value="Yes">Yes</option>
<option value="No">No</option></td>
</tr>
<tr>
<td>Firepit Availability</td>
<td><select name="firepit" value="<?php echo $firepit;?>">
<option value="Yes">Yes</option>
<option value="No">No</option></td>
</tr>
<tr>
<td>Site Description</td>
<td><input type="text" name="description" value="<?php echo
$description;?>"></td>
</tr>
<tr>
<td>Reservation Link</td>
<td><input type="url" name="reslink" value="<?php echo $reslink;?
>"></td>
</tr>
<td><input type="hidden" name="site" value="<?php echo
$_GET['site'];?>"></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
Sorry for the long code here, but I felt it was a little necessary to see the full context here.
There is also a break somewhere with the variables. The sitenumber variable isn't updating, and every variable after that is getting this error...
Notice: Undefined variable: videolink in C:\wamp\www\code\edit.php on line 124
So, this is kind of a two pronged problem. Help would be greatly appreciated.
Correct this :
$result = mysqli_query($mysqli, "SELECT * FROM sites WHERE sitenumber='".$sitenumber."' ");
And this :
$result = mysqli_query($mysqli, "UPDATE sites SET
sitenumber='$sitenumber',videolink='$videolink',daynight='$daynight',
maxtents='$maxtents',maxpersons='$maxpersons',geography='$geography',
view='$view',forestcover='$forestcover',waterfront='$waterfront',
firepit='$firepit',description='$description',reslink='$reslink' WHERE
sitenumber='$sitenumber'");
Your SQL query seems good, but the problem can come from the values of your variables.
Since your query is not escaped properly (and it should be for better security), I would advise you to debug your query before executing.
This way you will be able to understand what is going to be executed in your database.
If you don't use xdebug, you can just put your query into a variable and then dump it using var_dump.
Then, open phpmyadmin (I assume you have an access to it, at least), and paste the value of your variable (which is your query) into the SQL editor. Then execute it and you should have a message explaining where the error is.
It will help you understand why it is important to use prepared statement by seeing which variable has a wrong value (meaning it includes a ' or a ", for instance).
I hope it will help
I have a form with file upload and user name exits checking conditions.
What im facing it the data are not getting insert in mysql db. file as been successfully saved in given path. kindly help me on this im wasted already 2days with that i tried a lot myself.
form.php
<table style="text-align:right">
<form id="add" method="POST" action="action.php" enctype="multipart/form-data">
<tr>
<h4 class='bg-info'>
<br/>         Become a Member of jobportal and find the right job. Create your Profile now, Free!<br/><br/>
</h4>
</tr>
<tr>
<td></td>
<td> * Mandatory Fields </td>
</tr>
<tr>
<div class="col-md-1"></div>
<td>Enter Your Email-ID: *</td>
<td><input class="form-control input-sm" placeholder="Email ID" type="textfield" name="email"required></td>
</tr>
<tr>
<td>Choose password *</td>
<td><input class="form-control input-sm" placeholder="Enter Your Password" type="password" name="password"required/></td>
</tr>
<td>Re-Enter Your password *</td>
<td><input class="form-control input-sm" placeholder="Enter Your Password" type="password" name="repassword"required/></td>
</tr>
<tr>
<td> Please Enter Your Full Name:</td>
<td> <input class="form-control input-sm" placeholder="Enter Full Name" type="textfield" name="name"required></td>
</tr>
<tr>
<td>Your Current Location: *<td>
<select class="form-control input-sm" required name="location">
<option value='' disabled selected style='display:none;'>Select location *</option>
<option>Andhra Pradesh</option>
<option>Arunachal Pradesh</option>
<option>Assam</option>
<option>Bihar</option>
<option>Chhattisgarh</option>
<option>Goa</option>
<option>Gujarat</option>
<option>Haryana</option>
<option>Himachal Pradesh</option>
<option>Jammu and Kashmir</option>
<option>Jharkhand</option>
<option>Karnataka</option>
<option>Kerala</option>
<option>Madhya Pradesh</option>
<option>Maharashtra</option>
<option>Maharashtra</option>
<option>Manipur</option>
<option>Meghalaya</option>
<option>Mizoram</option>
<option>Nagaland</option>
<option>Odisha</option>
<option>Punjab</option>
<option>Rajasthan</option>
<option>Sikkim</option>
<option>Tamil Nadu</option>
<option>Telangana</option>
<option>Tripura</option>
<option>Uttar Pradesh</option>
<option>Uttarakhand</option>
<option>West Bengal</option>
</select></td>
</td>
</tr>
<tr>
<td>Enter Your Mobile Number: *</td>
<td><input class="form-control input-sm" placeholder="mobile number" type="textfield" name="mobilenumber" required/></td>
</tr>
<tr>
<td>Experience:</td>
<td>
<select class="form-control input-sm" required name="experience">
<option value='' disabled selected style='display:none;'>Select Experience</option>
<option>Fresher</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</td>
</tr>
<tr>
<td>Key Skill: *</td>
<td>
<input class="form-control input-sm" placeholder="Enter Your Skill" type="textfield" name="keyskill"/>
</td>
</tr>
<tr>
<td>Please Select your PG Degree</td>
<td>
<select class="form-control input-sm" required name="degree">
<option value='' disabled selected style='display:none;'>Select Degree</option>
<option>B.sc</option>
<option>B.E</option>
<option>B.Com</option>
<option>others</option>
</select>
</td>
</tr>
<tr>
<td>Please Select Higher Studies:</td>
<td>
<select class="form-control input-sm" required name="hsc">
<option value='' disabled selected style='display:none;'>Select Higher Studies</option>
<option>HSC</option>
<option>Diploma</option>
<option>ITI</option>
<option>others</option>
</select>
</td>
</tr>
<tr>
<td>Please Select your Gender: *</td>
<td>
<select class="form-control input-sm" required name="gender">
<option value='' disabled selected style='display:none;'>Select</option>
<option>Male</option>
<option>Female</option>
<option>others</option>
</select>
</td>
</tr>
<tr>
<td>Upload your Resume :</td>
<td><input type="file" name="filep"></td>
</tr>
<tr>
<td> </td>
<td>by clicking register u accepting our terms and condtions. click here !</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="add" class="btn btn-info btn-sm" id="add" value="Register With JobPortal">
</td>
</tr>
</form>
</table>
action.php
$con = mysqli_connect('localhost','root','');
if (!$con) {
die('Could not connect: ' . mysql_error());
} else {
echo 'connected';
}
if (isset($_POST['add']) ) {
if (!get_magic_quotes_gpc() ) {
$email = addslashes ($_POST['email']);
} else {
$email = $_POST['email'];
}
$email = $_POST['email'];
$password = md5 ($_POST['password']);
$name = $_POST['name'];
$location = $_POST['location'];
$mobilenumber = $_POST['mobilenumber'];
$experience = $_POST['experience'];
$keyskill = $_POST['keyskill'];
$degree = $_POST['degree'];
$hsc = $_POST['hsc'];
$gender = $_POST['gender'];
$resume = $_FILES['filep']['name'];
$folder = "C:/wamp/www/userlogin/pic/";
$name="SELECT emailid FROM userregistration WHERE emailid='$email'";
mysqli_select_db($con, 'login');
$result = mysqli_query($con, $name);
if (mysqli_num_rows($result)!=0) {
echo "Username already exists";
} else {
echo"data entered done";
}
if (move_uploaded_file($_FILES["filep"]["tmp_name"], $folder . $_FILES["filep"]["name"])) {
echo "images moved sus";
} else {
echo "not done";
}
echo "<p align=center>File ".$_FILES["filep"]["name"]."loaded...";
$sql = "INSERT INTO userregistration "
. "(email, password, name, location, mobilenumber, experience, keyskill, degree, hsc, gender, resume)"
. "VALUES('$email', '$password', '$name', '$location', '$mobilenumber', '$experience', '$keyskill',
'$degree', '$hsc', '$gender', '$resume')";
mysqli_select_db($con, 'login');
$retval = mysqli_query($con, $sql);
if (!$retval) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
echo' insert more data ';
mysqli_close($con);
}
What I exactly need is: I want to upload form data with the file url into database and need to check email id or name already exits.
I only get error in $sql = "insert into" portion other than else working fine.
Thanks in advance.
echo your sql query before
mysqli_select_db($con, 'login');
and execute it in your Mysql phpmyadmin...
I guess there is some problem in your query formation, spacing between words or something.
Errors
Missing database name
mysqli_connect("localhost","root","","login");
And error in $sql query
So final well-From code is
<?php
$con= mysqli_connect("localhost","root","","login");;//missing database
if (! $con)
{
die('Could not connect: ' . mysql_error());
}
else{
echo 'connected';
}
if(isset($_POST['add']))
{
if(! get_magic_quotes_gpc() )
{
$email = addslashes ($_POST['email']);
}
else
{
$email = $_POST['email'];
}
$email = $_POST['email'];
$password = md5 ($_POST['password']);
$name = $_POST['name'];
$location = $_POST['location'];
$mobilenumber = $_POST['mobilenumber'];
$experience = $_POST['experience'];
$keyskill = $_POST['keyskill'];
$degree = $_POST['degree'];
$hsc = $_POST['hsc'];
$gender = $_POST['gender'];
$resume = $_FILES['filep']['name'];
$folder = "C:/wamp/www/userlogin/pic/";
$query001="SELECT emailid FROM userregistration WHERE emailid='$email'";
$result = mysqli_query($con, $query001);
if(mysqli_num_rows($result)!=0){
echo "Username already exists";
}
else
{
echo"data entered done";
if (move_uploaded_file($_FILES["filep"]["tmp_name"], $folder . $_FILES["filep"]["name"]))
{
echo "images moved sus";
}
else
{
echo "not done";
}
echo "<p align=center>File ".$_FILES["filep"]["name"]."loaded...";
$sql = "INSERT INTO userregistration (email, password, name, location, mobilenumber, experience, keyskill,
degree, hsc, gender, resume) VALUES('$email','$password','$name','$location','$mobilenumber','$experience','$keyskill','$degree','$hsc','$gender','$resume')";
$retval = mysqli_query($con, $sql);
if(!$retval )
{
die('Could not enter data: ' . mysql_error());
}
else
{
echo "Entered data successfully\n";
echo' insert more data ';
mysqli_close($con);
}
}
}
?>
and be aware with MySQL Injection.
simply you can use mysqli_real_escape_string()
Example
$name = mysqli_real_escape_string($_POST['name']);
Tip from(Comment)
You have $name declared twice in your code - rename the $name select statement. ($name = $_POST['name']; and also $name="SELECT emailid FROM userregistration WHERE emailid='$email'"; ) – Jesse C
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.";
}
?>
Hey I need to get the gender selected from a select tag
and then store that value as a variable in php, here's some relevant snippets of both
the register.php form and the register_process.php file
register.php
<form action="register_process.php" method="post">
<table>
<tr>
<td>Username (to be used for login and display name)</td>
<td><input type="text" name="username" id="username" onclick="check()"/></td>
<td id="username_check"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" id="password" onclick="check()"/></td>
<td id="password_check"></td>
</tr>
<tr>
<td>Password (Re-Enter)</td>
<td><input type="password" name="repassword" id="repassword" onclick="check()"/></td>
<td id="repassword_check"></td>
</tr>
<tr>
<td>Email Address</td>
<td><input type="text" name="email" id="email" onclick="check()"/></td>
<td id="email_check"></td>
</tr>
<tr>
<td>Email Address (Re-Enter)</td>
<td><input type="text" name="reemail" id="reemail" onclick="check()"/></td>
<td id="reemail_check"></td>
</tr>
<tr>
<td>Gender</td>
<td>
<select name="gender">
<option value="1">Male</option>
<option value="2">Female</option>
</select>
</td>
<td></td>
</tr>
<tr>
<td>I agree to the terms and conditions</td>
<td><input type="checkbox" name="tos" id="tos" /></td>
<td id="tos_check"></td>
</tr>
<tr>
<td id="valid" colspan="3"></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Register" /></td>
</tr>
<tr>
<td colspan="3">Cancel</td>
</tr>
</table>
</form>
there is a ton of javascript I have omitted from this that does very basic validation
register_process.php
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
?>
<?php
$connection = mysql_connect(HOST, USERNAME, PASSWORD);
if(!$connection)
{
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db(DATABASE, $connection);
if(!$db_select)
{
die("Database selection failed: " . mysql_error());
}
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$repassword = mysql_real_escape_string($_POST['repassword']);
$email = mysql_real_escape_string($_POST['email']);
$reemail = mysql_real_escape_string($_POST['reemail']);
$gender = $_POST['gender'];
$tos = mysql_real_escape_string($_POST['tos']); // not being checked yet
$errors = 0;
$success = 0;
// USERNAME CHECK
if (preg_match('/^[a-z\d_]{5,20}$/i', $username))
{
$user_query = "SELECT * FROM users WHERE user_name = '$username' OR login_name = '$username' LIMIT 1";
$result=mysql_query($user_query);
$count=mysql_num_rows($result);
if($count==0)
{
echo "username is available <br/>";
$success++;
echo "<br/>1 Passed<br/>";
}
else
{
echo "sorry, that username already exist";
$errors++;
echo "<br/>1 Passed<br/>";
}
}
else
{
echo "You either need to enter a username, or you have entered a username in an incorrect format.";
$errors++;
echo "<br/>1 Passed<br/>";
}
// PASSWORD CHECK
if(preg_match('/^[a-z\d_]{5,20}$/i', $password))
{
// password is between 5-10 characters, alpha-numeric (a-z, A-Z, 0-9) and underscores
if($password === $repassword)
{
// password is identical
$success++;
echo "<br/>2 Passed<br/>";
}
else
{
// passwords do not match
$errors++;
echo "<br/>2 Passed<br/>";
}
}
else
{
echo "Password failed validation";
$errors++;
}
// EMAIL CHECK
if (eregi('^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$',$email))
{
// user#email.com passes
// 1#1.com passes
// -#_.com passes
//
echo "<br/> email is ok";
if($email === $reemail)
{
// email addresses match
$success++;
echo "<br/>3 Passed<br/>";
}
else
{
// email address does not match
echo "<br/>3 Passed<br/>";
$errors++;
}
}
else
{
echo "email validation failed <br/>";
$errors++;
echo $email;
}
// Here is the problem, I can't seem to evaluate the correct value,
// When I echo out $gender I get nothing, So theres either an issue
// in the html form OR in the way I use $gender = $_POST['gender'];
if($gender == 1 || $gender == "1" || $gender == '1')
{
echo "male selected";
}
else
{
echo "female selected";
}
?>
what am I missing here guys?,
I have been hunting around
google to find an answer with no success.
heres the error php is giving me:
"Notice: Undefined index: gender in register_process.php on line 22"
Everything else in the form IS working fine, there are no other issues
Your mistake is this:
/>
Don't close your form tag way up there - you need to close it after the select.
BTW xhtml is dead, don't use it (it has been superseded by html5). Use plain HTML and don't close tags that don't need it.
Because of error in your HTML syntax.
Change:
<form action="register_process.php" method="post" />
To:
<form action="register_process.php" method="post">