Well, I have the following problem: my little test website is near completion and all that’s left is PHP validation on submit. But there exactly lies my problem. I can’t seem to let it validate when the user clicks submit.
I searched plenty of websites but on all of those they submit the page to the same page, and I submit the page to a new page. I don’t know how different this is from the first method but I can’t seem to get it to work.
I have 5 fields in my form which need to be required:
<table>
<tr>
<td align="right">Naam:</td>
<td align="left"><input type="text" name="naam" onkeydown="return names(event)"/></td>
</tr>
<tr>
<td align="right">Woonplaats:</td>
<td align="left"><input type="text" name="woonplaats" onkeydown="return names(event)"/></td>
</tr>
<tr>
<td align="right">Straatnaam:</td>
<td align="left"><input type="text" name="straatnaam" onkeydown="return names(event)"/></td>
</tr>
<tr>
<td align="right">Huisnummer:</td>
<td align="left"><input type="text" class="formnumbers" name="huisnummer"/></td>
</tr>
<tr>
<td align="right">Telefoonnummer:</td>
<td align="left"><input type="text" name="telefoonnummer" onkeydown="return phonenumber(event)"/></td>
</tr>
</table>
That’s all. My form action is as follows:
<form action="?page=pizza_bestelling" method="post" name="orderform">
I know PHP validation should be really easy (at least that’s what I’ve heard) but I can’t seem to work it out myself, so that’s why I decided to ask it here.
Now all it needs to do is check if one of those 5 fields is empty, if so don’t submit. Otherwise submit.
(Keep in mind that I have 16 fields in my form, it counts only for these 5 specific, the other 11 can be empty)
I appreciate any help in this matter, since it’s all that’s left before completing my website!
Thanks in advance!
Upon submiting you will lose "?page=pizza_bestelling" of the link, you can set it in a hidden input with that value if you need it passed.
set the method to method="post" in the form
and on the same page you will need something like
function validate_form($data)
{
//rules that will end with return false; if they are not valid
// example
if (!isset($data["naam"]) || $data["naam"] == '') return false; // if the name is not set or it's empty
// return true if all validation checks are passed
return true;
}
if ($_SERVER["REQUEST_METHOD"] === "POST")
{
$form_data['naam'] = $_POST['naam'];
$form_data['woonplaats'] = $_POST['woonplaats'];
// and so forth for each variable
// run the validate_form function for the data you got through POST
validate_form($form_data);
}else
{
//form displayed here
}
You want to set up an errors array which will store any errors, and allow you to print them out if necessary.
Then you check each variable in the following manner:
$errors = array(); //initialise error array
if (empty($_POST['naam'])) {
$errors[] = 'You forgot to add a name';
} else {
$name = trim($_POST['naam']);
}
This checks if the naam input and writes a message to the errors array if it's empty, or assigns the value to the $name variable if not.
Once you've gone through all your inputs, you can then perform a check on the errors array:
if (empty($errors)) { // If everything's OK.
//do what you need to do
} else {
echo '<p>The following errors occurred:<br/>';
foreach ($errors as $msg) {
echo "$msg<br/>\n";
}
echo '<p>Please try again</p>';
}
This only checks for empty fields of course - you should implement more validation for valid emails etc. For useability purposes you should really look at a one-page solution with sticky fields though.
Do a for each as follows:
$allowed = array("naam","woonplaats","stratnaam","formnumbers","telefoonnummer");
foreach ($allowed as $key => $val){
if($_POST[$key] == "")
$errors = true;
}
if($errors){
// don't submit
}
else {
// submit
}
Related
So I have a PHP CRUD system which adds, edits and deletes entries from/to a database. The CMS in question is a drugs table. I can add drugs to this table using the add button and filling in a form, I can also delete the drugs by simply deleting them. But the one of issue is the edit/update part of the system.
The edit feature itself works fine, I'm able to edit an entry and it will post to the database and show up in the table because the user gets redirected back to the table page which shows all the drugs, however, when I remove the text from a field, leaving it empty, and press update, I get an error message which says a text field is empty, however, I also notice the id at the top of the page is no longer there which gives me an Undefined index:error.
I've narrowed the problem down to it being simply because the input type "submit" removes it for some reason.
URL before pressing update with a text field empty:
php_files/DrugEdit.php?Drug_ID=23
URL after pressing update with a text field empty:
eMAR/php_files/DrugEdit.php
How the program works (with code):
Php variable created by getting the Drug_ID from the URL (in this case 23)
$Drug_ID = $_GET['Drug_ID'];
Then gets the field data from the database and assigns them to variables
$result = mysqli_query($conn, "SELECT * FROM drugs WHERE Drug_ID=$Drug_ID");
while($res = mysqli_fetch_array($result))
{
$Drug_Name = $res['Drug_Name'];
$Allergies = $res['Allergies'];
$Side_effects = $res['Side_effects'];
$Type_of_Medication = $res['Type_of_Medication'];
$Dosage = $res['Dosage'];
}
?>
The data is then shown in a form where I can edit the data
<form name="form1" method="post" action="DrugEdit.php">
<table border="0">
<tr>
<td>Drug_Name <?php echo $drug_name_error ?></td>
<td><input type="text" Name="Drug_Name" value="<?php echo $Drug_Name;?>"></td>
</tr>
<tr>
<td>Allergies</td>
<td><input type="text" Name="Allergies" value="<?php echo $Allergies;?>"></td>
</tr>
<tr>
<td>Side_effects</td>
<td><input type="text" Name="Side_effects" value="<?php echo $Side_effects;?>"></td>
</tr>
<tr>
<td>Type_of_Medication</td>
<td><input type="text" Name="Type_of_Medication" value="<?php echo $Type_of_Medication;?>"></td>
</tr>
<tr>
<td>Dosage</td>
<td><input type="text" Name="Dosage" value="<?php echo $Dosage;?>"></td>
</tr>
<tr>
<td><input type="hidden" Name="Drug_ID" value=<?php echo $_GET['Drug_ID'];?>></td>
<td><input type="submit" Name="update" value="Update"> </td>
</tr>
</table>
</form>
If the update button gets pressed, it runs the block of code below:
$drug_name_error = " ";
if(isset($_POST['update']))
{
$Drug_ID = $_POST['Drug_ID'];
$Drug_Name=$_POST['Drug_Name'];
$Allergies=$_POST['Allergies'];
$Side_effects=$_POST['Side_effects'];
$Type_of_Medication=$_POST['Type_of_Medication'];
$Dosage=$_POST['Dosage'];
// checking empty fields
if(empty($Drug_Name) || empty($Allergies) || empty($Side_effects) || empty($Type_of_Medication) || empty($Dosage)) {
if(empty($Drug_Name)) {
$drug_name_error = "<font color='red'>Drug_Name field is empty.</font><br/>";
}
if(empty($Allergies)) {
echo "<font color='red'>Allergies field is empty.</font><br/>";
}
if(empty($Side_effects)) {
echo "<font color='red'>Side_effects field is empty.</font><br/>";
}
if(empty($Type_of_Medication)) {
echo "<font color='red'>Type_of_Medication field is empty.</font><br/>";
}
if(empty($Dosage)) {
echo "<font color='red'>Dosage field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($conn, "UPDATE drugs SET Drug_Name='$Drug_Name' ,Allergies='$Allergies' ,Side_effects='$Side_effects' ,Type_of_Medication='$Type_of_Medication',Dosage='$Dosage' WHERE Drug_ID=$Drug_ID");
//redirecting to the display page. In our case, it is index.php
header("Location: ../drug_manager.php");
}
}
Thank you for taking the time to read my problem. Hopefully I've provided enough information for you.
input type "submit" removes it for some reason
Because you're submitting the form, and the URL for the form submit action is defined in the <form> element:
<form name="form1" method="post" action="DrugEdit.php">
Note that there's no Drug_ID value on that URL. However, in the form processing code you're not looking for it in the URL, you're looking for it in the form post:
$Drug_ID = $_POST['Drug_ID'];
So I'm not really sure where you're getting that error. But if somewhere in your form logic you're also looking for $_GET['Drug_ID'], or simply want it to be on the URL for some downstream need, then you can just add it to that URL:
<form name="form1" method="post" action="DrugEdit.php?Drug_ID=<?php echo $_GET['Drug_ID'];?>">
I would like to pass variables through out three pages.
The method I am currently using is:
Fist Page has a form e.g. input type=”text” name=”username”
Second page receives input from form on first page with the $_POST function
e.g. $username=$_POST[“username”]
In order to keep the information from the first page stored, I created a session on the second page, and stored the input in it, e.g. as follows:
$_SESSION[“username”]=$username
I then navigate to the third page and start my session. If I echo the stored input from my session, the server returns “undefined variable username ”. I’m guessing this is so, because the variable $username is by definition $_POST[“username”], and in this case, there is no input for that post (being on the third page).
Of course I have tried converting the variable $username in a string and/or text with the print()/print_r() function. Doesn't change anything.
Does anyone have any solutions or workarounds to this issue?
I have come up with an unelegent way to solve the one problem: just recreate a copy of the form on the first page in the second page with the value=$_POST[“username”]…….but I need this to be a session, as these three pages are not linear (in other words, not steps 1,2,3, but steps 1,2,1,3 etc).
If it helps: this is a registration form (without passwords) with three pages. In the end, one must be able to navigate back to the pages to check ones inputs (so the data needs to be stored somewhere in order to call it up in the input fields).
Code page one (Inputs are in tables, left column specifies the what the Input is, right column the entry field):
<table>
<tr>
<td class="table_column_1"><p>Title </p></td>
<td>
<p><select name="title" class="dropdown" style="width:145px">
<option>Bitte waehlen</option>
<option value="Frau">Mr</option>
<option value="Herr">Mrs</option>
</select></p>
</td>
<tr>
<td class="table_column_1"><p>First name: </p></td>
<td><p><input type="text" name="firstname"</p>
</td>
</tr>
<tr>
<td><p>Surname: </p></td>
<td><p><input type="text" name="surname" /></p></td>
</tr>
<tr>
<td><p>Email: </p></td>
<td><p><input type="email" name="email" /></p></td>
</tr>
<tr>
<td><p>Company: </p></td>
<td><p><input type="text" name="company" /></p></td>
</tr>
<tr>
<td class="table_column_1"><p>Department: </p></td>
<td><p><input type="text" name="department" /></p></td>
</tr>
</table>
Code page two:
<?php
//Change variable to text/string
$title=print_r($_POST["title"]);
$firstname=print_r($_POST["firstname"]);
$surname=print_r($_POST["surname"]);
$email=print_r($_POST["email"]);
$company=print_r($_POST["company"]);
$department=print_r($_POST["department"]);
if ($title != "Bitte waehlen" && $firstname != "" && $surname != "" && $email != "" && $company != "" &&$department != ""){
session_start(1);
echo "Session: RUNNING";
//list for registration values
$_SESSION["registration"]="YES";
$_SESSION["title"]=$title;
$_SESSION["firstname"]=$firstname;
$_SESSION["surname"]=$surname;
$_SESSION["email"]=$email;
$_SESSION["company"]=$company;
$_SESSION["department"]=$department;
//Test session department and variable firstname validity
echo $_SESSION["department"];
echo $firstname;
}
else{
session_start(1);
$_SESSION["registration"]="NO";
echo "Session: NO";
header("location: registration.php");
};
?>
Code page three:
<?php
session_start(1);
echo "Session: RUNNING";
//Check if session department data is returnable => no
echo $_SESSION["department"];
?>
You'll have to show your code, but basically, this should work:
session_start();//before ANY output is sent to the client!
if (isset($_POST['username']))
{
$_SESSION['username'] = $_POST['username'];
}
if (!isset($_SESSION['username']))
{
//redirect, or present user with error message
}
$username = $_SESSION['username'];
This sets $_SESSION['username'] to the value of $_POST['username'] if that post value was sent, and assigns the value of $_SESSION['username'] to $username in all cases. if neither $_POST or $_SESSION have a username set, then there is an unexpected problem, and you should redirect, or show the user an error message...
After your code was posted, a couple of issues became obvious:
session_start expects no arguments, you're passing 1.
session_start can only be called when the headers haven't been sent (ie: no output), you're calling print_r, which creates output.
Don't use the closing ?> tag, if your script only contains PHP (see php.net if you want to know why)
Make sure there is no whitespace before the opening <?php tag
Functions return values for a reason: session_start returns false if the session couldn't be created: check return values
This means that your page2.php script should look like this, more or less:
<?php
if (!session_start())
exit('Output has already been sent!');//check for whitespace, use output buffering...
if (isset($_POST['title']) && $_POST['title'] !== 'Bitte waehlen')
{
$_SESSION['title'] = $_POST['title'];
$_SESSION["registration"]="YES";
//avoid notices, always use isset:
$_SESSION['firstname'] = isset($_POST['firstname']) ? $_POST['firstname'] : null;
}
else
{
//form wasn't submitted, or the title was "Bitte waehlen":
// show error message, or redirect
}
As far as I can understand you are using register globals.
Now that is your first error. Don't use it. Just don't.
Then, you are storing the username in a session, so now you can access it using
$_SESSION['username']
Also, when storing data in a session you also need to call session_start(); before assigning any data to your session.
I have a form which the user enters data eg first name and last name etc. I have PHP validation which checks for empty field. The problem is when the submit button is clicked, the whole form data is erased when a field is left empty.
I tried this method below.
<input type="text" value="<?php echo $_POST["UserName"]; ?>"" name="UserName"
id="UserName" size="20" />
But when the form loads for the first time, inside the text box is this
<br /><b>Notice</b>: Undefined index: UserName in ...... on line <b>477</b><br />
Is there a method to stop the form from being cleared? or to echo the data into the fields?
replace this :
value="<?php echo $_POST["UserName"]; ?>"
in your code with this :
<?php if(isset($_POST["UserName"])) echo $_POST["UserName"]; ?>
The issue here is that you're not checking whether $_POST["UserName"] is initialized, and when it is not, you'll throw the error. Check with isset:
<input type="text" value="<? if isset($_POST["UserName"]) { echo $_POST["UserName"]; } ?>" name="Givenname" id="Givenname" size="20" />
Check if $_POST["UserName"] isset, Try this:
<input type="text" value="<?php echo isset($_POST["UserName"]) ? $_POST["UserName"] : ''; ?>" name="Givenname"
id="Givenname" size="20" />
I think you are using Reset button like this:
<input type="reset" />
Try this:
<input type="submit" />
If you are trying Second one then use required in every input like:
<input required type="text" />
Your form is not being cleared or erased. But you are loading a NEW page with a NEW form.
Your attempt to load the new form is a good one, but you need to change
<input type="text" value="value="<?php echo $_POST["UserName"]; ?>"" name="UserName" id="UserName" size="20" />
into
<input type="text" value="<?php echo isset($_POST["UserName"])?$_POST["UserName"]:""; ?>" name="UserName" id="UserName" size="20" />
So remove the second value=" and the corresponding " which should have never been there. And check if the variable is available before trying to echo it.
In addition to doing this, you might also want to do client side validation in Javascript on top of the server side validation. (Never only do client side validation, by the way, as that can be fooled by end users.)
What you can do is to change your <form> tag into this:
<form action="..." method="post" onsubmit="if (document.getElementById('UserName').value == '') { alert('UserName is still empty'); return false; }">
This will prevent the form from being sent to PHP when UserName is still empty. And thus prevent from the page being reloaded and the form being cleared.
PHP forms will often discard entered data upon error validation, even when echoing it in the input field caches the entry on successful submit, and it is understandable that erasing disallowed data would be the default behavior. However, it can be a real hardship to retype large amounts of text in a textarea, and its sudden vanishing may come as an unwelcome surprise to the user, especially when due to a simple reason such as an over-the-character-number limit.
Setting the $_POST['UserName'] value with the error validation should preserve the field input without allowing its process. The example uses a variable to cache the data and echo it into the input field.
Update: The script has been updated to include multiple submit buttons for the same form, as well as the option for a success message array.
Update: The script has been updated to include an exit() option as well as a textarea.
UserName and First Name allowed characters are defined and will
trigger an error with uppercase A-Z or special characters.
UserName uses the error array, while First Name uses exit() to stop
the script altogether.
Textbox allowances also will trigger an error with uppercase A-Z or
special characters, and use exit() to stop the script.
The form data will be preserved on error message, exit() page return, and successful send.
The form results are printed on successful send.
<?php
/* Define variables and set to empty values.*/
$username=$first_name=$textbox='';
/* If using non-array success variable, initialize it as a string:
$success='';
Otherwise, define as an array. */
/* Submit button is clicked, start validation.
Separate multiple submit buttons (for the same form) with || (|| = OR):
*/
if ((isset($_POST['submit_one'])) || (isset($_POST['submit_two']))) {
// Define error and success messages as arrays to display in a list.
$error=array();
$success=array();
// Validate user input and error characters not lowercase a-z or 1-9.
if (!empty($_POST['UserName'])) {
/* Trim outside whitespace and sanitize user input.
A custom function or purifier could well be used. */
$username=trim(htmlspecialchars($_POST['UserName'], ENT_QUOTES));
if (preg_match("/^[a-z0-9]+$/", $username)) {
/*
if (preg_match("/^[a-z0-9]+$/", trim($_POST['UserName']))) {
$username=trim(htmlspecialchars($_POST['UserName'], ENT_QUOTES));
}
can be placed here instead, however input data will likely not be preserved on error. */
// Data is acceptable, continue processing...
}
else {
// Data is not accepted, set value to prevent loss on error and echo input without processing.
$error[]='User Name can only contain lowercase a-z and 0-9.';
$username=$username;
/* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether:
$username=$username;
exit ("Username may only contain lowercase a-z and 0-9. Use the Back-button to try again.");
*/
}
}
else {
$error[]="Please enter a User Name.";
}
if (!empty($_POST['first_name'])) {
/* Trim outside whitespace and sanitize user input.
A custom function or purifier could well be used. */
$first_name=trim(htmlspecialchars($_POST['first_name'], ENT_QUOTES));
if (preg_match("/^[a-z0-9]+$/", $first_name)) {
/*
if (preg_match("/^[a-z0-9]+$/", trim($_POST['first_name']))) {
$first_name=trim(htmlspecialchars($_POST['first_name'], ENT_QUOTES));
}
can be placed here instead, however input data will likely not be preserved on error. */
// Data is acceptable, continue processing...
}
else {
// Data is not accepted, set value to prevent loss on error and echo input without processing.
/* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether. */
$first_name=$first_name;
exit ("First Name may only contain lowercase a-z and 0-9. Use the Back-button to try again.");
/*
$error[]='First Name may only contain lowercase a-z and 0-9.';
$first_name=$first_name;
*/
}
}
else {
$error[]="Please enter a First Name.";
}
if (!empty($_POST['textbox'])) {
/* Trim outside whitespace and sanitize user input.
A custom function or purifier could well be used. */
$textbox=trim(htmlspecialchars($_POST['textbox'], ENT_QUOTES));
if (preg_match("/^[a-z0-9\ \(\s*\n){2}]+$/", $textbox)) {
/*
if (preg_match("/^[a-z0-9\ \(\s*\n){2}]+$/", trim($_POST['textbox']))) {
$textbox=trim(htmlspecialchars($_POST['textbox'], ENT_QUOTES));
}
can be placed here instead, however input data will likely not be preserved on error. */
// Data is acceptable, continue processing...
}
else {
// Data is not accepted, set value to prevent loss on error and echo input without processing.
/* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether. */
$textbox=$textbox;
exit ("Textbox input may only contain spaces, lowercase a-z, and 0-9. Use the Back-button to try again.");
/*
$error[]='Textbox input may only contain spaces, lowercase a-z, and 0-9.';
$textbox=$textbox;
*/
}
}
else {
$error[]="Please enter Textbox content.";
}
// If no errors, process data.
if (empty($error)) {
if (isset($_POST['submit_one'])) {
/* Sanitized submit button per rule #1: never trust user input. Remove sanitization if it causes a system error.
Reiterating ($_POST['submit'] is helpful when using multiple submit buttons.
Wrap each function in the additional submit isset, and end functions with closing (empty($error) else statement. */
$_POST['submit_one']=trim(htmlspecialchars($_POST['submit_one'], ENT_QUOTES));
/* Post data or send email, and print success message.
The array is option. Do not define as an array or use[] to use as a simple variable. */
// Processing data here, for example posting to a database ...
$success[]="The submit_one Send Form request has been processed!";
}
if (isset($_POST['submit_two'])) {
$_POST['submit_two']=trim(htmlspecialchars($_POST['submit_two'], ENT_QUOTES));
// Processing data here, for example sending an email ...
$success[]="The submit_two Process Form request has been sent!";
}
}
/* If errors, show error message.
The exit() option ends the script at the validation check .*/
else {
$error[]="Please correct the errors and try again.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.wrapper {margin: 2% auto; width: 500px;}
textarea {text-align:left;}
</style>
</head>
<body>
<div id="anchor" class="wrapper">
<div>
<form name="data_form" action="#anchor" method="post">
<table>
<tr>
<td colspan="2">
<label for="UserName">User Name</label>
<br>
<input type="text" name="UserName" id="UserName" size="20" value="<?php echo $username; ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<label for="first_name">First Name</label>
<br>
<input type="text" name="first_name" id="first_name" size="20" value="<?php echo $first_name; ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<label for="textbox">Textbox</label>
<textarea name="textbox" id="textbox" style="height:100px; width:98%;text-align:left;"><?php echo $textbox; ?></textarea>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit_one" id="submit_one" value="Send Form">
</td>
<td>
<input type="submit" name="submit_two" id="submit_two" value="Process Form">
</td>
</tr>
</table>
</form>
</div>
<div>
<?php
/* Print errors as a list or print success message.
Separate multiple submit buttons with ||. */
if ((isset($_POST['submit_one'])) || (isset($_POST['submit_two']))) {
if (!empty($error)) {
echo '<h4>The form was not sent due to the following errors:</h4>
<ul>';
foreach ($error as $message) {echo '<li>'. $message . '</li>';
}
echo '</ul>';
}
/* Print success confirmations as a list for processed input. */
else {
echo '<h4>The form has been sent!</h4>
<ul>';
foreach ($success as $message) {echo '<li>'. $message . '</li>';}
/* If using a success variable without defining it as an array,
initialize it as a variable at the top of the script,
then print variable without <ul>s and foreach loop:
echo '<p>' . $success . '</p>';
*/
echo '</ul>
<h4>Processed Data:</h4>
<ul>
<li>User Name: ' . $username . '</li>
<li>First Name: ' . $first_name . '</li>
<li>Textbox: <br>' .
/* Replace $textbox new lines with <br> tags. */
nl2br($textbox) .
'</li>
</ul>';
}
/* Unset foreach loop data. */
unset($message);
}
?>
</div>
</div>
</body>
</html>
I'm having trouble with this form. I want the user to be able to edit an item in the datebase. They chose which item they want to edit on one page and get sent with a GET to the editing page. The GET has the id of the item they need to edit.
The editing page loads with the details of the item inserted into the user form (apart from the name of the file) this field is left blank. I am trying to do some logic that checks if the user has chosen a file.
If they haven't then this field should be ignored as I will presume the user is happy with the file that is already uploaded.
If they chose a file then this means they want this to be the new picture. Only then do I want to run the logic to upload the picture and insert its name into the database.
I'm getting my POST details by saying:
$clean_pic = $_POST['pic'];
I am then saying if it's blank do nothing otherwise run the upload:
if($clean_pic = ''){}
else{
It's not working. Any ideas how I should find out if its blank? Cut down code:
if (isset($_POST['add']))
{
// validate 'pic': must consist of alphanumeric characters only.
$_POST['pic'] = isset($_POST['pic']) ? $_POST['pic'] : '';
//if(preg_match('/\.(jpg|gif|jpeg)$/i',$_POST['pic']))
//{
$clean_pic = $_POST['pic'];
//}
//else
//{$error++; $errmsg .= 'Invalid pic. ';}
}
if (isset($_POST['add']) && ($error==0))
{
if (!isset($_POST['pic'])) { echo"test1";}
else {echo"test222";}
/*tied this too but it didnt work (it will always display result 1):
if (!isset($_POST['pic'])) { echo"test1";}
if (isset($_POST['pic'])) {echo"test222";}*/
}
else //output error messages
{
/////////render form
?>
<form enctype="multipart/form-data" action="" method="post" id="save"><fieldset>
<table id="site-form">
<tr>
<td class="one_of_three"><label>Item Name: </label></td>
<td class="two_of_three"><input type="text" name="fileName" id="fileName" value="<?php echo"$db_name";?>"/></td>
<td><label class="errors" id="fileNameError"> </label></td>
</tr>
<tr>
<td class="one_of_three"><label>Picture: </label></td>
<td class="two_of_three"><input type="file" name="userfile[]" id="pic"/></td>
<td><label class="errors" id="picError"> </label></td>
</tr>
<tr>
<td class="one_of_three"> </td>
<td class="two_of_three"><input name="add" id="save_button" type="submit" value="Update"/> Cancel.</td>
<td> </td>
</tr>
</table>
</fieldset></form>
<?php }?>
What about if (!isset($_POST['pic']))?
You cant access the file using 'id' attribute ('pic'). You have to use the value of 'name' attribute ('userfile'). You can check whether the file is uploaded or not using $_FILES array in php.
if(isset($_FILES) && isset($_FILES['userfile']) && (trim($_FILES['userfile']['name']) != '') ) {
//Your upload code here
}
else
{
//No file uploaded
}
You need to check to things :
one is $_POST['pic'] is an array
second one is in the form you have to use enctype="multipart/form-data" attribute.
My issue is I have a PHP $_POST that returns a null or empty value, and I personally do not see any error with my code (but I know its there) and I can't really step away from it for a few hours since I am on a time schedule. So, I was hoping someone could help me out ;)
Here is what I have, basically:
<table border="0" align="center">
<tr>
<td>
<div id="lvl3">Project Name:</div>
</td>
<td>
<input type="text" name="prjname" maxlength="250">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Submit" name="prjsubmitname">
<input type="button" value="Cancel" onclick="$('#popupoverlay').hide(); $('#prjpopupbox').hide(); $('#prjname').hide(); $('#prjdescription').hide(); $('#prjversion').hide(); $('#prjrelease').hide();">
</td>
</tr>
This is my table for editing a project name- what is important here is the textbox input, I think.
Next I have my PHP:
//Did the user change the Project Name
if (isset($_POST['prjsubmitname']))
{
//Is the input empty
if (!trim($_POST['prjname']))
{
//Input is empty
echo('<script>senderror("Please enter a valid Project Name empty");</script>');
} else {
//Input isnt empty, assign variables
$url = geturlext();
$prjname = mysql_real_escape_string(trim($_POST['prjname']));
//Is input invalid
if (strcasecmp($prjname, "main") == 0 | $prjname == "404")
{
//Input is invalid
echo('<script>senderror("Please enter a valid Project Name invalid");</script>');
} else {
//Input is valid, connect to database
dbconnect();
$checkquery = mysql_query("SELECT * FROM projects WHERE name = '$prjname'") or die(mysql_error());
$check = mysql_num_rows($checkquery);
//Does Project Name already exist
if ($check == 0)
{
//No it does not
$updatequery = mysql_query("UPDATE projects SET name = '$prjname' WHERE name = '$url'") or die(mysql_error());
echo("<script>location.href='index.php?page=" . $prjname . "'</script>");
} else {
//Yes it does
echo('<script>senderror("That Project Name already exists");</script>');
}
}
}
}
This is where I get my issue; No matter what I enter in the textbox, I always get the error message for 'Input is empty'. I have printed the output of $_POST['prjname'] and it is indeed empty.
Now the weird part is, I have this exact same (at least I think) setup for changing the project description, and it works flawlessly. For the sake of comparison- i've included the same parts of the project description editor below.
The table:
<table border="0" align="center">
<tr>
<td>
<div id="lvl3">Project Description:</div>
</td>
<td>
<textarea type="text" name="prjdescription" maxlength="750" style="width:300px; height:100px; resize:none;"></textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Submit" name="prjsubmitdescription">
<input type="button" value="Cancel" onclick="$('#popupoverlay').hide(); $('#prjpopupbox').hide(); $('#prjname').hide(); $('#prjdescription').hide(); $('#prjversion').hide(); $('#prjrelease').hide();">
</td>
</tr>
And the PHP:
//Did the user change the Project Description
if (isset($_POST['prjsubmitdescription']))
{
//Is the input empty
if (!trim($_POST['prjdescription']))
{
//Input is empty
echo('<script>senderror("Please enter a valid Project Description");</script>');
} else {
//Input isnt empty, do stuff
$url = geturlext();
$prjdescription = mysql_real_escape_string(trim($_POST['prjdescription']));
//Connect and change description
dbconnect();
$updatequery = mysql_query("UPDATE projects SET description = '$prjdescription' WHERE name = '$url'") or die(mysql_error());
echo("<script>location.href='index.php?page=" . $url . "'</script>");
}
}
For clarification, both tables are in the same form tag, and the PHP is right next to eachother.
No errors on Firebug, matter of fact Firebug doesn't give me anything. Other than that, I'm sure it's some really small typo that I am overlooking.
I have found a solution to this issue:
Renaming the variable '$prjname' in the Project Name editing PHP fixes the issue.
It would seem that having a variable ($prjname) with the same name as a $_POST (['prjname']) returns an empty or null string. No idea why.
Thanks to those who tried to help
EDIT: Actually, I get the error again if I only change the variable name ($prjname)- It only fixes when I change the $_POST name... Odd.
Looking at the description of above issue, we can conclude that form elements must be encapsulated within form tag ,then only form data will be posted to server.
So as a solution to your problem, you need to define input elements within form tag.