Warning: Undefined array key even when I'm not using array - php

I have the following code:
<form action="calculator.php" method="get">
<label for="age">Enter your age</label>
<input type="number" id="age" name="age">
<br>
<label for="height">Enter your height</label>
<input type="number" id="height" name="height">
<br>
<input type="submit">
</form>
<?php
$age = $_GET["age"];
$height = $_GET["height"];
if (isset($age) && isset($height)) {
echo ($age + $height);
}
?>
This gives me the warnings: Warning: Undefined array key "age" in (file location) and Undefined array key "height" in (file location).
As you can see I'm not using arrays. I googled this and tried putting the echo statement inside an if ( isset() ), but it still gives me the same warning.
Can someone tell me why and how to fix this?

$_GET is an empty array on this case that's why they are undefined keys.
You should check if $_GET has age and height.
You can do something like this:
if(isset($_GET['age'], $_GET['height'])){
// do the calculation
}

Try using extract function.
<?php
extract($_GET);
/*$age = $_GET["age"];
$height = $_GET["height"];
*/
if (isset($age) && isset($height)) {
echo ($age + $height);
}
?>

Related

Unidentified index while echoing out else

I'm new to PHP and i've been learning PhP like a week ago so please bear with me.
While i was trying to echo out an else statement if any variable in the POST request is different or not set.
<form action="process.php" method="POST">
<p> <input type="radio" name="language" value="PHP"> PHP <br>
<input type="radio" name="language" value="RUBY"> RUBY <br>
<input type="radio" name="language" value="HTML"> HTML <br>
</p>
<input type="Submit" value="Submit">
</form>
process.php
<?php
$lang = $_POST['language'];
if (isset($lang)) {
echo $lang;
}
else {
echo 'Buzz off';
}
?>
While its showing error like :
Notice: Undefined index: language in
/Applications/XAMPP/xamppfiles/htdocs/process.php on line 2
Please help :)
You're trying to get an undefined array index and put it into a variable, and this will throw an exception.
You should check if the array key isset before you try to put it in a variable, like this:
if ($_POST['language']) {
$lang = $_POST['language'];
echo $lang;
}
else {
echo 'Buzz off';
}
If you are using PHP7, you can use the Null coalescing operator.
$lang = $_POST['language'] ?? 'Buzz off';
echo $lang;

input box displays undefined variable when page loads [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 5 years ago.
I have a 4 input boxes, 3 are hidden fields. The first input box take a figure, while the second displays 20% of the figure and the 3rd displays the answer gotten from subtracting 20% of the initial figure from the figure. here is a typical example of what i mean.
textbox A = 100
20% of 100 = 20.
textbox B = 20.
100 - 20 = 80.
textbox C = 80
i have been able to do all this and passed the variables to the input box, but when i load the page it populates the textbox with undefined variable and when i click on the button it execute the script and the initial text that says undefined variable is inserted into my db. how do i post the answer into my db instead of post what loads with the page.
here is my code.
When it loads up:
<?php
if (isset($_POST['amount'])&& ($_POST['iniamount']) &&
($_POST['outamount'])) {
$amount = $_POST['amount'];
$iamount = 0.2;
$inimain = $iamount * $amount;
$outamount = $amount - $inimain;
}
$date = date("Y-m-d H:i:s");
?>
here is the form
<div class="form">
<form method="POST" enctype="multipart/form-data" name="donation" class="" >
<div class="form-group ">
<label for="cname" class="control-label col-lg-2">Donation Amount <span class="required">*</span></label>
<div class="col-lg-10">
<input class="form-control" id="amount" name="amount" type="text" required />
<input name="email" type="hidden" class="form-control" id="email" required />
<input name="iniamount" type="text" class="form-control" id="iniamount" value="<?php echo $inimain; ?>" required />
<input name="outamount" type="text" class="form-control" id="outamount" value="<?php echo $outamount; ?>" required />
<input name="date" type="hidden" class="form-control" id="outamount" value="<?php echo $date; ?>" required />
</div>
<?php
$amount = 0.0;
$iamount = 0.0;
$inimain = 0.0;
$outamount = 0.0;
if (isset($_POST['amount'])&& ($_POST['iniamount']) && ($_POST['outamount'])) {
$amount = $_POST['amount'];
$iamount = 0.2;
$inimain = $iamount * $amount;
$outamount = $amount - $inimain;
}
$date = date("Y-m-d H:i:s");
?>
The problem is from the variables.
Initiate the variables. Actually not like this because it is for calculation.
but if you do like this and when the textboxs are empty it will cause undefine error.The system will not knw how to deal with it.
$inimain = '';
$outamount = '';
This is the correct way.
$amount = 0.0;
$iamount = 0.0;
$inimain = 0.0;
$outamount = 0.0;
<input name="iniamount" type="text" class="form-control" id="iniamount" value="<?php if(isset($_POST['iniamount'])){echo $inimain;} ?>" required />
<input name="outamount" type="text" class="form-control" id="outamount" value="<?php if(isset($_POST['$outamount'])){echo $outamount;} ?>" required />
<input name="date" type="hidden" class="form-control" id="outamount" value="<?php if(isset($_POST['$date'])){echo $date;} ?>" required />
Initialize the variable first
While The accepted answer will work, I think initializing the variable before hand will serve you better in the long run.
<?php
$inimain = '';
$outamount = '';
// repeat for any other variable you might need in your form
if (isset($_POST['amount'])&& ($_POST['iniamount']) && ($_POST['outamount'])) {
$amount = $_POST['amount'];
$iamount = 0.2;
$inimain = $iamount * $amount;
$outamount = $amount - $inimain;
}
$date = date("Y-m-d H:i:s");
?>
This will allow you to keep your HTML form simple and easy to read and will allow you more flexibility in the future, for example if you want to set a default value for certain input fields.

mysql UPDATE variable

Hi guys i have code like this
include('db.php');
if (isset($_POST['save']) && $_POST['save'] == '') {
if(isset($_POST['misamarti'])){ $misamarti = $_POST['misamarti']; }
if(isset($_POST['teleponi'])) { $teleponi = $_POST['teleponi']; }
if(isset($_POST['posta'])) { $posta = $_POST['posta']; }
if(isset($_POST['paqsi'])) { $paqsi = $_POST['paqsi'];}
$query = "UPDATE contact SET `misamarti` = ".$misamarti.", `teleponi` = ".$teleponi.", `posta` = ".$posta.", `paqsi` = ".$paqsi." WHERE `contact`.`id` =1;";
$result = mysql_query($query);
}
<form method="post" action="" enctype="multipart/form-data">
<input type="hidden" name="about" value="template1" />
<input type="text" value="" name"misamarti" />
<input type="text" value="" name"teleponi" />
<input type="text" value="" name"posta" />
<input type="text" value="" name"paqsi" />
<input type="submit" value="" name="save" />
and result is
Notice: Undefined variable: misamarti in C:\xampp\htdocs\Template\admin_panel\contact.php on line 18
Notice: Undefined variable: teleponi in C:\xampp\htdocs\Template\admin_panel\contact.php on line 18
Notice: Undefined variable: posta in C:\xampp\htdocs\Template\admin_panel\contact.php on line 18
Notice: Undefined variable: paqsi in C:\xampp\htdocs\Template\admin_panel\contact.php on line 18
if anyone know why is this error pls comment.
You're using the variables even if they weren't submitted with the form, and update the fields in the db with those undefined varaibles, so you'll be destroying any data that was in the DB previously.
If nothing else, you need to at least set a default value for the fields, e.g:
$misamarti = isset($_POST['misamarti']) ? $_POST['misamarti'] : '';
^^--default empty string
And then realize that you are WIDE OPEN to an sql injection attack. You are BEGGING to get your server pwn3d.
As you can see in your HTML code, you have the names bad written, they have to be written this way: name="misamarti". You forgot the equal (=) between name and the name. If you see the rest of attributes, like text and value, you see that theres an equal, that's the correct way of setting attributes.

Can't get the $_POST Variable

It should be a multiple upload form for pictures
I get the HTML Code for a Upload-Form:
<form action="upload.php" method="post" id="uploadform" name="uploadform" enctype="multipart/form-data">
<label id="filelabel" for="fileselect">Choose the Pictures</label>
<input type="file" id="fileselect" class="fileuplaod" name="uploads[]" multiple />
<span class="text">Exist Album</span><br />
<select id="existAlbum" name="existAlbum" size="1">
<option value="noAlbum">SELECT ALBUM</option>
</select>
<span class="text">OR</span>
<span class="text">New Album</span><br />
<input id="newAlbum" name="newAlbum" type="text" maxlength="20" placeholder="ALBUM NAME"/>
<input type="submit">
</form>
The form link to the uploaded.php. But there i get:
Notice: Undefined index: existAlbum in E:\xampp\htdocs\fotokurs\upload\upload.php on line 11
Notice: Undefined index: newAlbum in E:\xampp\htdocs\fotokurs\upload\upload.php on line 12
Here's the upload.php:
<?PHP
$allowedExtensions = array('png', 'jpg', 'jpeg');
$maxSize = 20971520;
$i = 0;
$first = 0;
$exist_album = $_POST['existAlbum'];
$new_album = $_POST['newAlbum'];
Where is my fault? I can't find it...
EDIT
Add following to my code:
if( isset( $_POST['existAlbum'] ) or isset( $_POST['newAlbum'] ) ){
$exist_album = $_POST['existAlbum'];
$new_album = $_POST['newAlbum'];
}else{
echo 'no album <br />';
}
print_r($_POST);
new output:
no album
Array ( )
Notice: Undefined variable: new_album in E:\xampp\htdocs\fotokurs\upload\upload.php on line 20
Notice: Undefined variable: exist_album in E:\xampp\htdocs\fotokurs\upload\upload.php on line 21
Notice: Undefined variable: new_album in E:\xampp\htdocs\fotokurs\upload\upload.php on line 22
Notice: Undefined variable: exist_album in E:\xampp\htdocs\fotokurs\upload\upload.php on line 23
One of your issues is that existAlbum has no actual values associated with it.
You have <option>Select Album</option> which has no value associated with the option element. If there is no value associated, the select element is not posted to the server. You should change it to be:
<option value="">Select Album</option>
EDIT
Since the user only has to supply one or the other, you should use the following to set your variables:
$existsAlbum = (isset($_POST['existAlbum']) && !empty($_POST['existAlbum'])) ? $_POST['existAlbum'] : 'defaultValue';
$newAlbum = (isset($_POST['newAlbum']) && !empty($_POST['newAlbum'])) ? $_POST['newAlbum'] : 'defaultValue';
One important thing to note is that Internet Explorer does not support the placeholder attribute.
EDIT 2
Here is my quick test page that worked test.php:
<form action="upload.php" method="post" id="uploadform" name="uploadform" enctype="multipart/form-data">
<label id="filelabel" for="fileselect">Choose the Pictures</label>
<input type="file" id="fileselect" class="fileuplaod" name="uploads[]" multiple />
<span class="text">Exist Album</span><br />
<select id="existAlbum" name="existAlbum" size="1">
<option value="noAlbum">SELECT ALBUM</option>
</select>
<span class="text">OR</span>
<span class="text">New Album</span><br />
<input id="newAlbum" name="newAlbum" type="text" maxlength="20" placeholder="ALBUM NAME"/>
<input type="submit" value="Submit">
</form>
upload.php
<pre>
<?php print_r($_POST); ?>
<?php print_r($_FILES); ?>
</pre>
results
Array
(
[existAlbum] => noAlbum
[newAlbum] =>
)
Array
(
[uploads] => Array
(
//Contents here
)
)
Try if the value existAlbum get set, because it won't return any value if you there is nothing picked. You could give the existAlbum picker a default='1' or something:
if isset($_POST['existAlbum']){
echo 'yes';
}
else{
echo 'no';
}
I think that there is something wrong with the rule enctype="multipart/form-data". Try to just remove this, it should be set automatically by your browser.
You have no value for the option select album, even if you don't intend that option to be used give it a value such as 0 so that it will always be set in the POST variables.
<option value="0">SELECT ALBUM</option>
<option value="some album">Some Album</option>
...
If select is not picked you will not get it at all (you expect it to be empty, which is not true). You have to check first
$exist_album = isset($_POST['existAlbum']) ? $_POST['existAlbum'] : '<DEFAULT VALUE>';
and same for checkbox.
The newAlbum thing should work as text inputs are always there. See
print_r($_POST);
to see what's really in there, and in my case it is - on "empty" submit I get:
Array
(
[existAlbum] => SELECT ALBUM
[newAlbum] =>
)
BTW: you should use <?php rather than <?PHP.
print $_POST Array using print_r($_POST); Make sure your form action is correct
<form action="upload.php" method="post" id="uploadform" name="uploadform" enctype="multipart/form-data">

Undefined index error PHP

I'm new in PHP and I'm getting this error:
Notice: Undefined index: productid in /var/www/test/modifyform.php on
line 32
Notice: Undefined index: name in /var/www/test/modifyform.php on line
33
Notice: Undefined index: price in /var/www/test/modifyform.php on line
34
Notice: Undefined index: description in /var/www/test/modifyform.php
on line 35
I couldn't find any solution online, so maybe someone can help me.
Here is the code:
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<input type="hidden" name="rowID" value="<?php echo $rowID;?>">
<p>
Product ID:<br />
<input type="text" name="productid" size="8" maxlength="8" value="<?php echo $productid;?>" />
</p>
<p>
Name:<br />
<input type="text" name="name" size="25" maxlength="25" value="<?php echo $name;?>" />
</p>
<p>
Price:<br />
<input type="text" name="price" size="6" maxlength="6" value="<?php echo $price;?>" />
</p>
<p>
Description:<br />
<textarea name="description" rows="5" cols="30">
<?php echo $description;?></textarea>
</p>
<p>
<input type="submit" name="submit" value="Submit!" />
</p>
</form>
<?php
if (isset($_POST['submit'])) {
$rowID = $_POST['rowID'];
$productid = $_POST['productid']; //this is line 32 and so on...
$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
}
What I do after that (or at least I'm trying) is to update a table in MySQL.
I really can't understand why $rowID is defined while the other variables aren't.
Thank you for taking your time to answer me.
Cheers!
Try:
<?php
if (isset($_POST['name'])) {
$name = $_POST['name'];
}
if (isset($_POST['price'])) {
$price = $_POST['price'];
}
if (isset($_POST['description'])) {
$description = $_POST['description'];
}
?>
Apparently the index 'productid' is missing from your html form.
Inspect your html inputs first. eg <input type="text" name="productid" value="">
But this will handle the current error PHP is raising.
$rowID = isset($_POST['rowID']) ? $_POST['rowID'] : '';
$productid = isset($_POST['productid']) ? $_POST['productid'] : '';
$name = isset($_POST['name']) ? $_POST['name'] : '';
$price = isset($_POST['price']) ? $_POST['price'] : '';
$description = isset($_POST['description']) ? $_POST['description'] : '';
This is happening because your PHP code is getting executed before the form gets posted.
To avoid this wrap your PHP code in following if statement and it will handle the rest no need to set if statements for each variables
if(isset($_POST) && array_key_exists('name_of_your_submit_input',$_POST))
{
//process PHP Code
}
else
{
//do nothing
}
TRY
<?php
$rowID=$productid=$name=$price=$description="";
if (isset($_POST['submit'])) {
$rowID = $_POST['rowID'];
$productid = $_POST['productid']; //this is line 32 and so on...
$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
}
There should be the problem, when you generate the <form>. I bet the variables $name, $price are NULL or empty string when you echo them into the value of the <input> field. Empty input fields are not sent by the browser, so $_POST will not have their keys.
Anyway, you can check that with isset().
Test variables with the following:
if(isset($_POST['key'])) ? $variable=$_POST['key'] : $variable=NULL
You better set it to NULL, because
NULL value represents a variable with no value.
Hey this is happening because u r trying to display value before assignnig it
U just fill in the values and submit form it will display correct output
Or u can write ur php code below form tags
It ll run without any errors
If you are using wamp server , then i recommend you to use xampp server .
you . i get this error in less than i minute but i resolved this by using (isset) function . and i get no error .
and after that i remove (isset) function and i don,t see any error.
by the way i am using xampp server
this error occurred sometime method attribute ( valid passing method )
Error option :
method="get" but called by $Fname = $_POST["name"];
or
method="post" but called by $Fname = $_GET["name"];
More info visit http://www.doordie.co.in/index.php
To remove this error, in your html form you should do the following in enctype:
<form enctype="multipart/form-data">
The following down is the cause of that error i.e if you start with form-data in enctype, so you should start with multipart:
<form enctype="form-data/multipart">

Categories