Reputation: 69
I have a HTML form and PHP script on the same page, which calculates a price based in the input from the HTML form.
It is important that the information provided in the form is stored when the PHP script runs, so that the customer can see what the price is based on.
The following code stores the text input:
<input type="number" min="1" max="420" name="stofprijs" width="100" placeholder="Prijs" value="<?=( isset( $_POST['stofprijs'] ) ? $_POST['stofprijs'] : '' )?>"> euro.
I had tried to store the data from the drop down list with this code:
On top:
<?php
$gordijnsoort = $_POST['gordijnsoort'];
?>
In the form:
<select name="gordijnsoort">
<option value="gordijn" <?php echo $gordijnsoort == 'gordijn' ? 'selected="selected"' : ''; ?>>Gordijn</option>
<option value="vouwgordijn" <?php echo $gordijnsoort == 'vouwgordijn' ? 'selected="selected"' : ''; ?>>Vouwgordijn</option>
<option value="ringgordijn" <?php echo $gordijnsoort == 'ringgordijn' ? 'selected="selected"' : ''; ?>>Ringgordijn</option>
</select>
The data is stored, but the empty form keeps displaying the error:
Undefined index: gordijnsoort
The form should only save the variable when the customer submits the form, but now it's already looking for the variable at the start.
Does anyone know how to fix this?
Upvotes: 0
Views: 71
Reputation: 81
I think you will have to check if $_POST['gordijnsoort']
isset. Your code should look like:
$gordijnsoort = "";
if(isset($_POST['gordijnsoort'])
$gordijnsoort = $_POST['gordijnsoort'];
This will prevent callign non existing index before sending the form.
Upvotes: 0
Reputation: 2585
Thats because $_POST
is empty. It will only be filled after you submit your form. So first you have to check with isset
, empty
if gordijnsoort
exists.
E.g.
$gordijnsoort = isset($_POST['gordijnsoort']) ? $_POST['gordijnsoort'] : '';
Upvotes: 1
Reputation: 1151
Set your variable to NULL if it doesn't exist.
$gordijnsoort = isset($_POST['gordijnsoort']) ? $_POST['gordijnsoort'] : NULL;
Upvotes: 0
Reputation: 4616
Try this:
<?php
$gordijnsoort = array_key_exists('gordijnsoort', $_POST) ? $_POST['gordijnsoort'] : "";
?>
You will receive the error because at first call the $_POST
array is empty and you try to access a undefined key.
Upvotes: 1