I want to process form input into a MYSQL database but I am having trouble getting other files to recognize data in the _POST array and keep getting the typical "Undefined index" error.
My form:
<?php
$category = '';
$item = '';
// Check if form is posted
if (isset($_POST['item'])){
// Declare POST'd values into variables
$category = $_POST['Category'];
$item = $_POST['item'];
}
?>
<!-- Item Input form -->
<form id='additem' method='post' action="">
<fieldset>
<legend>Add Item</legend>
<table>
<tr>
<td><label for='Category'>Category: </label></td>
<td><input type='text' name='Category' list='categories' value='<?php $category;?>' /></td>
<datalist id='categories'>
<option value='Protein'>
<option value='Produce'>
<option value='Baked Goods'>
<option value='Dry/Canned'>
<option value='Household'>
</datalist>
</tr><tr>
<td><label for='item'>Name: </label></td>
<td><input type='text' name='item' value='<?php $item;?>' /></td>
</tr><tr>
<td></td><td><input type='Submit' value='Submit' /></td>
</tr>
</table>
</fieldset>
</form>
When I use $_POST in this file, it works perfectly fine but when I try to use it in another file, process.php:
<?php
echo $_POST['Category'];
echo '<br>';
echo $_POST['item'];
?>
it gives:
Notice: Undefined index: Category in E:\Documents\XAMPP\htdocs\Website\process.php on line 3
Notice: Undefined index: item in E:\Documents\XAMPP\htdocs\Website\process.php on line 5
Now I know my _POST array is not empty, because I can access it within my original form file. If I change the form action to "process.php" it works, but also automatically takes me to that page. What I want is for process.php to send data to my database while the form returns to its own page ready for more input. I have even literally copy and pasted the code from that example into files and attempted to run those, but I get similar errors so I think it might be an issue with XAMPP/Apache.
To address this, I have also tried this but post_max_size was already set to 8M, and as per another post I saw somewhere I added 'variables_order = "EGPCS"' in the line below. Still I am getting the same undefined index.
Is there something wrong with my code? Is it XAMPP/Apache? I have tried fresh installing XAMPP, but the issue still persists.
Your $_POST array will not be accessible on all pages.
As much as I have understood your problem , You are trying to access $_POST array on some other file , and this can only be used in this file or the file you post to.
You need to use SESSION in order to use these values
After POST Assign your values like this
$_SESSION["Category"] = $_POST['Category'];
Then on any other page just use
session_start(); on the top of page and then print your variable like
echo "Selected Category is " . $_SESSION["Category"] . ".<br>";
You have not specified the location or file in the action attribute of form element. The file specified in the action attribute can have the values of the form in &_POST[] global array. To access the values across multiple page you should use the cookies
Put check on
category
as you are only checking the
item
in array and if category is not present in array then it will give undefined index error so try the following ways
$category = '';
$item = '';
if (isset($_POST['item']) && isset($_POST['Category'])){
// Declare POST'd values into variables
$category = $_POST['Category'];
$item = $_POST['item'];
}
or if you want you can check them in different conditions
$category = '';
$item = '';
if (isset($_POST['item'])){
// Declare POST'd values into variables
$item = $_POST['item'];
}
if (isset($_POST['Category'])){
// Declare POST'd values into variables
$category = $_POST['Category'];
}
Related
I have done my research and cannot find an answer so now I'm here to seek out professionals' advice.
I have a query which returns an array in model:
$sql = "SalesList ";
$sql = $sql."'".$current_company_code."', ";
$sql = $sql."'".trim($current_user_id)."', ";
$sql = $sql."'".$as_date."', ";
$sql = $sql.$language_no;
$DB=$this->load->database($current_database,TRUE);
$query = $DB->query($sql);
return $query->result();
In controller: I passed the result to $data['sales_list'] and load to view
$data['sales_list'] = $this->SalesList->GetSalesList($current_database,$current_company_code,$current_user_id,date('Y-m-d 23:59:59'),$language_no);
$this->load->view('Sales_Record', $data);
In view:
<?php foreach ($sales_list as $record): ?>
<input type="hidden" name="sp_name_d[]" id="sp_name_d[]" value="<?php echo set_value('sp_name_d[]',trim($record->sp_name));?>"/>
<?php endforeach; ?>
Problem:
Upon submit, the same coding (which presents no issue on first load) prompted the following error:
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Line Number: 39
Array"/>
Line no 39 refers to:
<input type="hidden" name="sp_name_d[]" id="sp_name_d[]" value="<?php echo set_value('sp_name_d[]',trim($record->sp_name));?>"/>
Help needed. Thank you.
Sincerely, blossoming programmer.
[Update] Cause of issue (Rookie mistake):
I have some codes in view that use index in set_value (for radio button reference) which leads to multidimensional array:
<input type="radio" name="status_d[<?php echo $counter;?>]" id="status_d[]" value="1" <?php echo set_value('status_d['.$counter.']', '1', $record->status==1); ?> checked />
Solution:
in view added index in set_value:
<input type="hidden" name="sp_name_d[]" id="sp_name_d[]" value="<?php echo set_value('sp_name_d['.$counter.']',trim($record->sp_name));?>"/>
The Problem is:
set_value() - The first time there is no input so it becomes an empty string, but after submit it is an array which remains array.
On an Fresh load of a page there is no previous input data, So everything is empty in Form When setting via set_value.
I am developing a form in PHP. There are variables which are fix which will be displayed in the link of the web page. But some variable which are passed to other page are in hidden and are not fixed.
Eg.
http://editform.php?var1=23&var2=34 will have hidden variables hidvar=23
http://editform.php?var1=23 this will not have any hidden variable and also var2 is also not there
I have checked for variable in link with isset function.
if(isset($_GET['var2']))
now how to get all the variables values in another page with all combination of hidden variables and variable in Link.
I am further adding code which let you get the Idea what I need. Below web page is saved as webform.php
<?PHP
if(isset($_GET['YID']))
{ $YRID=$_GET["YID"]; }
else
{ $YRID=0; echo "Variable Missing. Program terminated."; }
?>
// GET THE VALUE OF $PASS;
//GET THE VALUE OF SESSIONID;
//GET THE VALUE OF YID.
<form action="WEBFORM.php?PASS=<?PHP echo $PASS;?>" name="FORM1" METHOD="POST">
<?php
//statement which do some operation using $YRID;
?>
<input type="hidden" name="SESSIONID" VALUE="<?PHP echo $SESID; ?>" />
</FORM>
while (list($key, $value) = each($_REQUEST))
{
echo ($key.' '.$value);
}
Where $key is the variable name, $value is variable value
I have tried the below code
isset($_POST['SUBMIT'])
if form is submitted then above code will check the variable which are hidden.
for checking the hidden variables and for the variable in link i have checked using below code
if(isset($_GET['YID']))
if form is not yet submitted then above code will check the variable.
I wrote a simple php script that basically echos the values put into a form on the page, later, I will have this write to a DB but I was working on troubleshooting it before I did that since I keep getting this warning.
Does anyone know why I am getting it? If I just fill in the fields and submit the form, the script works fine and the warning disappears.
PHP Function:
function quickEntry()
{
$subTitle = $_POST['subTitle'];
$subDetails = $_POST['details']; //This is line 13 in my code
echo "$subTitle";
echo "<br>$subDetails";
}
HTML / PHP Code:
<form method="post" action="">
<hr>
<h1>Quick Entry:<p></h1>
Subject Title:<br> <input type="text" name="subTitle"><br><br>
Subject Details: <p><textarea name="details" placeholder="Enter Details here..."></textarea><p><br>
<input type="submit" name="QuickEntrySubmit" value="Submit Quick Entry" /><br>
</form>
<?php
if (isset($_POST['QuickEntrySubmit']))
{
quickEntry();
}
?>
I know that I could disable warnings and I wouldn't see this, but I really just want to know why php is throwing the warning so I can fix the syntax appropriately and keep my code clean going forward. Full warning is:
Notice: Undefined index: details in C:\xampp\htdocs\test1.php on line 13
Thanks!
The reason why you are getting that error is because you are not checking whether the 'subTitle' and 'details' inputs have values in them.
Your code should work well like this:
function quickEntry(){
$subTitle = isset($_POST['subTitle'])? $_POST['subTitle']: null;
$subDetails = isset($_POST['details'])? $_POST['details']: null ; //This is line 13 in my code
if(!is_null($subTitle) && !is_null($subDetails)){
echo "$subTitle";
echo "<br>$subDetails";
} else{
//blah blah blah
}
You get the warnings because the $_POST variables with the indexes that you're checking for ($_POST['subTitle'] & $_POST['details']) aren't set, so the variables are empty as you reference something that isn't there.
You should do a check to ensure they are set first before trying to assign them to a variable:
$subTitle = (isset($_POST['subTitle']) && !empty($_POST['subTitle'])) ? $_POST['subTitle'] : null;
$subDetails = (isset($_POST['details']) && !empty($_POST['details'])) ? $_POST['details'] : null;
The above code will check to ensure the post index isset() and isn't empty() before assigning it to the variables.
NOTE
The variables are set when you submit the form because you are actually posting the data to the script.
You see the input attribute name? When you submit the form, they are the relevant $_POST indexes.
Just remember to ensure that the values aren't empty if you intend to print them to the markup.
I am trying run a small PHP script. I get an error when I try to run this small PHP line:
<?PHP print $firstname ; ?> within the html code. According to my tutorial guide this line in the value element should ensure that I keep any input text entered into the text fields even after I refresh the browser, but it does not! the following error message occurs:
Notice: Undefined variable: surname in C:\wamp\www\pages\basicForm.php
on line 27 Call Stack #TimeMemoryFunctionLocation 10.0007366504{main}(
)..\basicForm.php:0 " NAME="surname">
Why?
and the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<?PHP
if (!empty($_POST)) {
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
print($firstname);
print($surname);
}
else {
} print( 'welcomes');
?>
</head>
<body>
<Form name ="form1" Method ="POST" Action ="basicForm.php">
<label>
<INPUT TYPE = 'TEXT' Name ='firstname' VALUE="<?PHP print $firstname ; ?>">
</label>
<p>
<label>
<INPUT TYPE="TEXT" VALUE="<?PHP print($surname); ?>" NAME="surname">
</label>
<p>
<Input Type = "Submit" Name = "Submit1" Value = "Login">
</FORM>
</body>
</html>
All you need to assign initial value as below
$firstname = '';
$surname = '';
Relying on the default value of an uninitialized variable is
problematic in the case of including one file into another which uses
the same variable name. It is also a major security risk with
register_globals turned on. E_NOTICE level error is issued in case of
working with uninitialized variables, however not in the case of
appending elements to the uninitialized array. isset() language
construct can be used to detect if a variable has been already
initialized.
Read more in detail: PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"
$surname isn't set at first:
<INPUT TYPE="TEXT" VALUE="<?PHP print($surname);
It's only getting set at the top if $_POST is NOT empty.
if the $_POST variable is empty then $surname will not be created. There are a couple of ways that you can get around this.
1, predefine your variables:
$firstname = '';
$surname = '';
if (!empty($_POST)) {
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
}else {
}
2, Use ternary syntax:
$firstname = isset($_POST['firstname']) ? $_POST['firstname'] : '';
$surname = isset($_POST['surname']) ? $_POST['surname'] : '';
Both will ensure that your variables are created before printing them.
According to my tutorial guide this line in the value element should ensure that I keep any input text entered into the text fields even after I refresh the browser
It seems you misunderstood your tutorial.
Server side technology can't help until you actually send something to the server.
So, it seems you're just entering your values and refreshing your page before submit. Although some browsers may preserve entered values by their own will, but server side PHP has nothing to do with it.
Another story if you populate your form with values that's already on the server - such filled form will persists even refreshes.
I am trying to get some data from page to page and then mail them.
So from one form I am getting a title of item :
//Form1
<form class="orderFormFields" method="post" action="order">
<input type="hidden" name="productName" value="<?php the_title(); ?>">
<input class="oButton" value="Order" type="submit"/>
</form>
And then is another form (next page) with other fields witch I need to mail :
<?php
//getting a variable from previous form
$product = $_POST['productName'];
if(isset($_POST['submit']))
{
$name = $_POST['order_name'];
$mail = $_POST['email'];
$phone = $_POST['mobile'];
$date = $_POST['date'];
$comment = $_POST['comment'];
//simple mail function goes here
$done = true;
}
?>
//Form2 goes here
So if I insert <?php echo $product; ?> before if(isset($_POST['submit'])) I can see my variable from previous page and all works just find. But when I am inserting that same variable in mail function witch is inside if(isset($_POST['submit'])) , I cant mail that variable, seems like it is empty.
Does form method POST delete all previous form data? Because, if I change my Form1 method to GET and $product = $_POST['productName']; to $product = $_GET['productName']; I am getting that variable after Form2 submit and I can mail that variable. But I would like to prefer using POST method, because of nice URL.
You forgot to name your submit button so there is no $_POST['submit']
<input class="oButton" value="Order" type="submit" name="submit" />
EDIT:
Okay, $_POST is array and have its values only after the post request. If you make another post request or change the page the previous values of $_POST are deleted and these from the new request are stored.
You can store data from the first post in the sessions for example -
$_SESSION['postData']['form1'] = $_POST;