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

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.

Related

How to display divs after checking password with an HTML form

I'm programming a simple password checker with a html form, where you input the code and this code is compared as hash to another hashed code in the database. If the password matches, the index.php file shows a few divs, which otherwise are completely hidden from the user.
I've tried things like:
$input = "";
<center>
<form action="" method="GET">
CODE:<br>
<input type="text" name="code" value="">
<br><br>
<input type="submit" value="Submit">
</form>
</center>
<?php
$checker = new Checker();
$input = $_GET['code'];
//echo "<style>.Main_Content{ visibility:hidden;}</style>";
if ($checker->compareWords($input, 'Beginners')) {
echo "success Beginners<br>";
include 'Beginners_Video.php';
echo "<style>.Main_Content{ visibility:show;}</style>";
}
else {
echo "false Beginners<br>";
}
?>
Fatal error: Uncaught TypeError: Argument 1 passed to
Checker::compareWords() must be of the type string, null given, called
in D:\www\www91\members\members.php on line 64 and defined in
D:\www\www91\members\checker.php:23 Stack trace: #0
D:\www\www91\members\members.php(64): Checker->compareWords(NULL,
'Beginners') #1 {main} thrown in D:\www\www91\members\checker.php on
line 23
The result should be no error and just the whole thing hidden, or the output "False Beginners. Nothing else"
I know that i'm just stupid and that the answer is probably really simple. I've tried and I can't figure it out.
Thanks for your help.
Your code should work once you filled in and submitted the form, but there is no check handling the case where $_GET['code'] is unset or empty. Change your if statement to
if (!empty($input) && $checker->compareWords($input, 'Beginners')) {
in order to check for this first. If !empty($input) is false, the next condition won't be checked at all, so there won't be an error message and it will jump to the else clause directly.
On a side note: You should think about whether GET is the right method for what you're trying to achieve or whether POST would be better. With GET, The codes users enter might get saved in the browser's history and be visible to others using the same computer. Also, for passwords use type="password" for the input instead of displaying it in cleartext.
And one more thing: the <center> tag is deprecated and you should use CSS instead for layout.
At the very beginning you should check if something is passed in code parameter, using the isset() method. If $_GET['code'] is empty it will return null and this is why you get must be of the type string, null given.
<?php
if(isset($_GET['code']) {
$input = $_GET['code'];
} else {
// 'code' parameter is empty
$input = '';
}
$checker = new Checker();
// ...

How can i pass the variable in the anchor to the next page?

I have two pages where one links one to the other. How can i pass the value of the variable(region_name) in my anchor(select.php) to the next page(display.php)? i used the following codes and im getting Notice: Undefined variable: region_name.how do i fix it?
select.php
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a name="region_name" method="POST" value="Greater Accra Region" type="submit" href="display.php" target="main">Greater Accra Region</a>
</h4>
</div>
</div>
display.php
<?php
ob_start();
session_start();
if(isset($_POST['region_name'])){
$region_name = $_POST['region_name'];
}
$con=mysqli_connect("localhost","root","root","findings");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT * FROM approved_reservation WHERE region_name = '$region_name'";
$records=mysqli_query($con,$sql);
?>
We pass the variable $myVar through the URL and use $_GET in the next page to use it. We use htmlspecialchars(); to clean user input.
We use the if (isset($_GET['myVar'])) so it doesn't throw Notice: Undefined index error.
pageOne.php
<?php
$myVar = "My variable one.";
echo "<a href='pageTwo.php?myVar=" . $myVar . "'>Page Two</a>"
?>
pageTwo.php
<?php
if (isset($_GET['myVar'])) {
$myVar = htmlspecialchars($_GET['myVar'], ENT_QUOTES);
// Now you can use $myVar.
}
?>
Now I'm not sure what variable you want to pass through so I used a simple skeleton which I made yesterday to show you how it is done. If you supply more code, I'll edit it to suit your scenario.
Edit 1
Your code below is incorrect because you're declaring your variable $region_name inside the scope of the if statement your queries and other code which is dependent on the variable has to be in that if statement.
Another solution would be to define an empty variable $region_name outside of the if statement then after the if statement you won't get the error Undefined Index.
if(isset($_POST['region_name'])){
$region_name = $_POST['region_name'];
}
Edit 2
That error is being thrown for two reasons,
Your not actually passing the region name through the URL - though even if you were it wouldn't work as you're using $_POST instead of $_GET.
I outlined reason 2 in the above edit. You're using a variable which isn't in the scope of the queries.
You're getting an undefined variable because of the following:
href does not use methods, nor values, nor type, <form>...</form> does.
Forms use inputs with name attributes set for its method.
Your code is expecting it to be passed via a form and using a POST method.
More on forms here http://php.net/manual/en/tutorial.forms.php
What you want to use here is a GET in your conditional statement:
if(isset($_GET['region_name']) && !empty($_GET['region_name']) ){
$region_name = $_GET['region_name'];
echo $region_name;
}
Sidenote: I used !empty() should someone want to modify the URL as ?region_name=
and using a ? parameter after the filename and a = followed by the "value" you wish it to be:
Greater Accra Region
which in turn will echo "your_value".
You will need to modify its value respectively.
In your case, that would read as:
Greater Accra Region
You can also add to the above and inside the conditional statement:
if($_GET['region_name'] == "Greater Accra Region"){
echo "Region is Greater Accra Region";
}
Which can be modified as:
Sidenote: The following example checks if a region equals to something, and if the value was modified in the URL such as ?region_name=.
if(isset($_GET['region_name'])){
$region_name = $_GET['region_name'];
echo $region_name;
if($_GET['region_name'] == "Greater Accra Region"){
echo "Region is Greater Accra Region"; }
if(empty($_GET['region_name'])){
echo "EMPTY"; }
}
Now, seeing your query, that is unknown as to what the ultimate goal is.
Only you know and goes beyond the scope of your original question.
If you have a form (with a POST method) that you haven't posted, then you can use an input:
I.e.:
Greater Accra Region:
<input name="region_name" value="Greater Accra Region" type="submit">
and using your present POST arrays.
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
The simplest form of passing along the data to display.php would be to add the region_name to the URL like so:
href="displayApprovedReservation.php?region_name=<?php echo $region_name; ?>"
In the display.php, you would then use $_GET['region_name'] to retrieve the data from the URL. Doing it this way, you would need to make sure you sanitize the input as it can be changed very easily from the URL by a user.
The reason you are getting the error Notice: Undefined variable: region_name is because the data is not being posted to the page, therefore $_POST['region_name'] is not set, thus not setting $region_name in the process -- yet you are still calling it in the SQL query regardless of the variable being set:
$sql="SELECT * FROM approved_reservation WHERE region_name = '$region_name'";
There are several ways to do what you're trying to do. The method that you're trying to achieve would require a form like:
<form name="selection" method="POST" action="display.php">
<input name="region" type="radio" value="Greater Accra Region">
</form>
But it doesn't look great and don't work the way you want to.
Another method would be just to use a get variable like this
Greater Accra Region
Then on your display file you can use the variable $_GET['selection']; to use your selection :)

Undefined value when calling an input from a HTML form from PHP

Getting some issues with my PHP. I'm trying to get assign the value from the text box to a variable so that I can check it against a random number.
This is me initializing my variables:
session_start();
if (!isset ($_SESSION["rand"])) {
$_SESSION["rand"] = rand(0,100);}
$rand = $_SESSION["rand"];
if(!isset ($_SESSION["att"])) {
$_SESSION["att"] = 0;}
This is the form itself:
<form method="post">
<input type="text" id="guess" name="guess"/>
<input type="submit" value="Guess"/>
</form>
and this is the part that is causing the problem:
$answer = htmlspecialchars(trim($_POST["guess"]));
This is the error I'm receiving
I'm trying to achieve it to say nothing really, I know that it's because guess hasn't had anything defined to it but I'm not really sure what to define it while I don't need it.
Since you're using everything in one file <form method="post"> is what gave it away, since the action defaults to "self" if omitted, therefore you need to use a conditional isset() or !empty().
Consult my "footnotes" also.
I.e.:
if(isset($_POST["guess"])){
$answer = htmlspecialchars(trim($_POST["guess"]));
}
or
if(!empty($_POST["guess"])){
$answer = htmlspecialchars(trim($_POST["guess"]));
}
References:
http://php.net/manual/en/function.isset.php
http://php.net/manual/en/function.empty.php
Footnotes:
Even if you were to split those up into two seperate files, it would be best to still use a conditional isset() or !empty().
Use a conditional isset(). It is used to check if a variable is set or not.
When you initially load the page, your POST data is not set and that is the reason why you got that notice.
if(isset($_POST["guess"]) && $_POST["guess"] !=""){
$answer = htmlspecialchars(trim($_POST["guess"]));
}

ISSET function undefined variables variables

Hello i have problem with isset id like someone to help me fixin this problem. Its this problem Notice: Undefined variable: v in C:\xampp\htdocs\something\something2.php on line 17 and my code is :
<form id="priklad" method="post">
<label>Obvod kruhu:</label>
<?php IF (isset($_POST['v'])) {
$_POST['v'];
}
?>
<label>r:</label><input type="text" name="r"/>
<input type="submit" value="Vypočti"/></br>
<label><?php echo 2*$v;?> cm</label>
</form>
EDIT:
<form id="priklad" method="post">
<label>Obvod kruhu:</label>
<?php If (is_numeric($_POST['v'])) {
$v = $_POST['v'];
}
?>
<label>v:</label><input type="text" name="v"/>
<input type="submit" value="Vypočti"/></br>
<label><?php echo 2*$v;?> cm</label>
</form>
and im getting these errors
Notice: Undefined index: v in C:\xampp\htdocs\something\something2.php on line 11 and Notice: Undefined variable: v in C:\xampp\htdocs\something\something2.php on line 17
What's actually happening with that error is that your variable $v isn't being initialized because the code has not enter the if condition.
if(is_numeric($_POST['v'])){
$v = $_POST['v'];
}
You're assuming that the condition is_numeric($_POST..) is true but it might not be, which means that the variable $v is never initialized. Therefore is pretty normal the error you are having.
You can continue with your condition but you must check for the variable after it.
if(is_numeric($_POST['v'])){
$v = $_POST['v'];
}
echo 2 * (isset($v) ? $v : 1);
The above code might be improved. A better code/logic would be you to set up the default value of the variable in case the is_numeric returns false.
$v = 1; // default value
if(is_numeric($_POST['v'])){
$v = $_POST['v'];
}
echo 2 * $v;
What is happening is that your value v is not the same as the implied value of $_POST['v'] . As stated by Tim, there is no $v = statement so in effect your echo output is outputting nothing multiplied by 2.
This throws a warning which you have picked up.
So a solution could be:
<form id="priklad" method="post">
<label>Obvod kruhu:</label>
<?php If (is_numeric($_POST['v'])) {
$v = $_POST['v'];
}
?>
<label>r:</label><input type="text" name="r"/>
<input type="submit" value="Vypočti"/></br>
<label><?php echo 2*$v;?> cm</label>
</form>
I have used is_numeric as you are using the echo to produce a value x 2 so makes more sense to check V is a number rather than a string.
UPDATE
Ok, first stop then is to see what is on line 11? is it $_POST['v'] ? If so then you can work back to the source of the cause - replace the line 11 (comment it out, don't delete it) with something like:
print_r($_POST);
This will output all values associated with the array $_POST.
If you do not see a value for 'v' (and I guess you probably won't) then that means this value wasn't set in the previous HTML page so go back and check that your form submits an input such as:
<input name='v' value="something">
Undefined index means the array ( $_POST ) does not contain any information stored under $_POST['v'].
Can you confirm your POST is as intended, and that you do want post which means you need to submit the form rather than GET or another method, such as index.php?v=10 ?
The Notice:
PHP does have notice statements but they're only notices, they are not errors or even warnings, it's just PHP telling you what's going on. This will not break your code, but it could be nice to add this line above your IF statement:
$v = 0;
This establishes the variable $v and gives it a value. Which if $_POST['v'] exists is then updated to reflect that.
Your code must be like this.
<form id="priklad" method="post">
<label>Obvod kruhu:</label>
<?php
$v = '';
If (is_numeric($_POST['v'])) {
$v = $_POST['v'];
}
?>
<label>v:</label><input type="text" name="v"/>
<input type="submit" value="Vypočti"/></br>
<label><?php echo (($v)? 2*$v : 'Its not numeric value');?> cm</label>
</form>

Cannot get posted variables to echo in the form

It seems my code is correct, however the posted variables in the form will not echo in the update user settings page in the form. I have echoed the posted ids from the input in the database but I cannot get the variables to show.
I have done this in Codeigniter fine but am trying to do it in pure php with my own framework.
$users = new Users($db); comes from my init.php file that is called at the beginning of the file below.
when I
<?php var_dump($user['first_name'])?>
I get Null
<input type="text" name="first_name" value="<?php if (isset($_POST['first_name']) )
{echo htmlentities(strip_tags($_POST['first_name']));} else { echo
$user['first_name']; }?>">
Hoi Stephen,
Try print_r($_POST["first_name"]); instead of var_dump();
or just for all:
print_r($_POST);
best regards ....
add this at the top of your html page
#extract($_REQUEST);
and put is just to check and after checking remove the below line
print_r($_REQUEST);
hope this help .

Categories