Simple php calculator error (new to this!) [duplicate] - php

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 8 years ago.
When I say 'new', I mean that this is just about the first time I'm attempting php.
Anyway. I keep getting this error notice "Undefined index: type in c:\x\calculator.php on line 33", but it still echoes "You forgot to pick mathtype!" and the calculator works fine. This error notice occurs only when I don't select any radio box for math type (+-/*).
//Part of the form
<form action="calculator.php" method="post">
<input type="text" name="1stnumber">
<input type="text" name="2ndnumber">
<input type="radio" name="type" value="addition">
<input type="radio" name="type" value="subtraction">
<input type="submit" name="send">
<?php
//My variables
$number = $_POST['1stnumber']
$numbero = $_POST['2ndnumber']
$mathtype = $_POST['type'] /* **<-line 33** */
//The calculation part of the form here, which is working
//Tell the user if he didn't pick a math type (+-)
if(is_null($mathtype)){
echo "You forgot to pick mathtype!"
}
?>
Tried with elseif as well.. I don't see what's wrong between line 33 and the if(is_null()) line!
Sorry if it looks poor, messy, or if something doesn't make sense. Might be a few typos as well. Any help is appreciated.

Simply check if type is posted before you pick it up
if(isset($_POST['type']))
{
$mathtype = $_POST['type'];
}
else
{
echo "Type was not selected";
}

Set a default selected option, using the checked attribute.
<label><input type="radio" name="type" value="addition" checked="checked"> +</label>
<label><input type="radio" name="type" value="subtraction"> -</label>
Don't forget inputs needs labels in html if left out you can use a placeholder attribute, but that's clearly not possible with type="radio"; therefore wrap the input in a label with the text description next to it eg + or -
Also, is this a copy and paste error, bc all php statements must be terminated with a semicolon ;
$number = $_POST['1stnumber']; // <- terminate
$numbero = $_POST['2ndnumber']; // <- terminate
$mathtype = $_POST['type']; // <- terminate
echo "You forgot to pick mathtype!"; // <- terminate

It's always good practice to check if the variable you're trying to retrieve from $_POST has actually been set, try this:
<?php
//My variables
if (isset($_POST['1stnumber'])) {
$number = $_POST['1stnumber'];
}
if (isset($_POST['2ndnumber'])) {
$numbero = $_POST['2ndnumber'];
}
if (isset($_POST['type'])) {
$mathtype = $_POST['type']; /* **<-line 33** */
}
//The calculation part of the form here, which is working
//Tell the user if he didn't pick a math type (+-)
if (is_null($mathtype)) {
echo "You forgot to pick mathtype!";
}
?>

Check if the form is posted:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
//My variables
$number = $_POST['1stnumber']
$numbero = $_POST['2ndnumber']
$mathtype = $_POST['type'] /* **<-line 33** */
//The calculation part of the form here, which is working
//Tell the user if he didn't pick a math type (+-)
if(is_null($mathtype)){
echo "You forgot to pick mathtype!"
}
}
?>
Else the is_null check will also be executed on the first load (before the form has been posted).

Related

PHP: trouble passing objects through session [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)
How to use store and use session variables across pages?
(8 answers)
Closed 2 years ago.
I am building a program that makes a user enter three items into a cart, takes them to a page that says the items were added to the cart, and has a link to the cart which lists the items the user entered earlier. Here is my code:
Form:
<h3>Add Products To Cart</h3>
<form action="add_to_cart.php" method="post">
Item 1: <input type="text" name="item1"><br />
Item 2: <input type="text" name="item2"><br />
Item 3: <input type="text" name="item3"><br />
<input type="submit">
</form>
page that confirms adding was successful:
<?php
session_start();
$username = "Hubert";
$item1 = "cookies";
$item2 = "cream";
$item3 = "water";
if( ( strcasecmp($_POST["item1"], $item1 ) == 0 && strcasecmp($_POST["item2"], $item2) ) == 0 )
{
$_SESSION["logged"] = true;
$_SESSION["ID"] = $username;
echo "Items added to the cart". "<br />";
echo "Show items in the cart ";
}
else
{
echo "Try again";
}
?>
Page that lists items in cart:
<?php
session_start();
if( isset($_SESSION["logged"]) && $_SESSION["logged"] ){
echo "Item 1: ".$_POST["item1"]."<br />";
echo "Item 2: ".$_POST["item2"]."<br />";
echo "Item 3: ".$_POST["item3"]."<br />";
}
?>
The first two scripts work fine, however, in the 3rd script I have an error: : "Undefined index: items 1,2,3". Can someone offer a solution?
This happens because your $_POST array is filled with values only after you submit a form. So you get your values on the add_to_card.php page, but not on the next page you link to, it's just impossible.
What you need to do here is either to store your items in the database or (probably you wanted this one) to store them in the session itself. And then, on your third page (i.e., "What's in cart") use $_SESSION, and not $_POST superglobal.

PHP Getting a value form a form in POST that has values from a PHP script [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 4 years ago.
I created some PHP code to get values from a database and show them as an option in a form I created using HTML. Now I want to be able to select one of those options and then process that in POST. But it gives me an error that my index is undefined when I try to get that value in POST. So I guess my question is, is getting this value possible? If so, how would I accomplish this?
Here is my code:
<form method="post" action="dayzconfigedit.php">
<select name="item1">;
<?php
//Display the Items from the database in a dropdown menu
$sql = "SELECT item_id FROM `all_items`";
$result = $conn->query($sql);
for($x = 0; $x < $result->num_rows; $x++) {
$row = $result->fetch_assoc();
echo "<option value=\"{$row["item_id"]}\">{$row["item_id"]}</option>";
}
?>
</select>
</form>
Then I try to get value in POST:
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
//Grab Selected Items from Form
$item1 = "$_POST[item1]";
}
Thanks in advance!
I skimmed through the post that supposedly answers my question but I still can't solve this issue because I don't know why the index is undefined in the POST array.
You need to grab item 1 like this;
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
//Grab Selected Items from Form
$item1 = ! empty($_POST['item1']) ? $_POST['item1'] : null;
}
Also, please update where you echo the option to be;
echo"<option value=\"{$row["item_id"]}\">{$row["item_id"]}</option>";
You may either missed to specify method="post" in form tag .. or you missed to specify the name of the field <select> tag like <select name="item1">.
Now you can access the submitted value in $_POST["item1"]
I am not well versed in PHP but i think your code should read
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
//Grab Selected Items from Form
$item1 = $_POST["item1"]; //Take note of this line
}

PHP Session Variable will not change [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 6 years ago.
I have a form that consists of 4 radio buttons, each radio button represents a different shape either cuboid, cone, cylinder or sphere, I also have a session variable for each of those shapes ( each one is set to 0), when a user selects a radio button and submits the form I want it to add 1 to whatever shape was selected here is my code
HTML
<form action="question2.php" method="post">
<input type="radio" name="ans" value="cuboid">
<input type="radio" name="ans" value="cone">
<input type="radio" name="ans" value="cylinder">
<input type="radio" name="ans" value="sphere">
<input type="submit" value="Submit">
</form>
PHP
<?php
if(isset($_POST['submit'])) {
if(isset( $_POST['ans'])) {
$selected_answer = $_POST['ans'];
if($selected_answer == "cuboid") {
$_SESSION["cuboid"] = ((int)Session["cuboid"]) + 1;
}
}
}
?>
However this is not working. $_SESSION["cuboid"] just stays 0. Can anyone tell me where I am going wrong?
EDIT - I am defining the Session variable in a previous page like this
$_SESSION["cuboid"] = 0;
And also I have the following at the top of all my pages
<?php
session_start();
?>
You need to use use session_start, if you haven't done so already.
You also have a syntax error which should be showing if you have a error reporting enabled.
Change,
$_SESSION["cuboid"] = ((int)Session["cuboid"]) + 1;
To,
$_SESSION["cuboid"] = ((int)$_SESSION["cuboid"]) + 1;
Another thing...
Your if (isset($_POST['submit'])) conditional check will never run, as you have not actually set the name property for it.
Error Reporting
To enable error reporting to see any errors that you make,
error_reporting(-1);
ini_set('display_errors', 'On');

What could be wrong with this php code? [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 7 years ago.
i'm doing a voting system. After displaying all candidates from my DB, a user is to click on a candidate's image to vote.
I am trying to use GET to get the matric number of a candidate so as to echo a text.
The Error is this: Upon loading the page, an error message comes up even without clicking on any image as follows-
Notice: Undefined index: user in C:\xampp\htdocs\projects\onlinevoting\vote.php on line 74
Voted
What could be wrong?
if (isset($_POST['display'])) {
$position_selected = $_POST['position_selected'];
$sql = "SELECT * FROM candidate WHERE position='$position_selected'";
$run_query = mysqli_query($db_conn, $sql);
if (mysqli_num_rows($run_query) > 0) {
$nr = mysqli_num_rows($run_query);
echo '<h3 style="font-size:2em;text-align:center">('.$nr.') ASPIRANTS FOR <span style="color:maroon;text-decoration:underline"> '.$position_selected.'</span></h3>';
while ($row = mysqli_fetch_array($run_query)) {
echo '<div class="asp">
<a class="votelink" href="?user='.$row["matno"].'"><img title="Click Image to Vote" height="300" width="300" src="data:image;base64,'.$row[6].' "></a><br><p style="font-weight:bolder;font-size:1.5em;width:300px;text-align:center;margin-bottom:0px;">'.$row[1].'<br><b><p style="font-size:1em;font-weight:bold;width:300px;text-align:center;margin-bottom:0px;">'.$row[2].'/'.$row[3].'</p><b><br>
</div>';
}
if ($_GET['user'] == $row["matno"]) {
echo 'Voted';
}
} else {
echo '<p style="color:darkred;font-weight:bolder;font-size:1.6em;text-align:center;">No candidate for this Position</p>';
}
}
?>
From what you've posted I am going to guess that you're not checking that the $_GET variable user has been set.
Change this line
if ($_GET['user'] == $row["matno"]) {
to
if ((isset($_GET['user'])) && ($_GET['user'] == $row["matno"])) {
Posting this as an answer rather than a comment.
You are "trying to use GET to get the matric number of a candidate", however, at the top of your code, you are testing for if
(isset($_POST['display'])) {
using the POST super global, and nested within it you have
if ($_GET['user'] == $row["matno"]) {.
While it is actually possible to have such a situation, I believe that's where your problem stems from. What method is your form using: GET or POST? If GET, why the isset($_POST) test. If POST, does the form's action attribute have the user variable in its query string? You could begin to troubleshoot the problem from here.
Basically, PHP is reporting that the 'user' array member isn't set, which most likely means your form's action page does not include the user variable in its query string.
I propose two possible solutions to this.
First, and most preferably, use a hidden input field in your form, and set its value to the user's id. Then, instead of testing for $_GET['user'], test for $_POST['user']. The HTML snippet for the hidden input field would be like :
<input type="hidden" name="user" value="Whatever_user_id_is"/>
Then replace
if ($_GET['user'] == $row["matno"]) {
with
if ($_POST['user'] == $row["matno"]) {.
An alternative approach, if you wish to stick with the if ($_GET['user'] == $row["matno"]) { syntax/pattern, is to include the user variable as part of the form's action attribute:
<form method="post" action="YOUR_FORMS_ACTION_PAGE?user=what_ever_user_is">
That way, when you submit the form, the user variable will be present in the GET super global array.
That should be better
if (isset($_POST['user'])) {
if ($_POST['user'] == $row["matno"])) {
}
}

php throwing undefined index warning but the script works as intended?

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.

Categories