PHP - Undefined index - $_POST hidden input - php

I'm a beginner at coding, and I have to make a small game in php for school.
I have to use a hidden input, like this:
<form action="process.php" method="post">
<input type="hidden" name="rand" value="<?php rand(1,10); ?>" />
</form>
The value stands for a random number between 1 and 10 (I hope the value is correct). Now, in process.php I want to retrieve the random number by using post, so what I tried to do is the following:
<?php $random = $_POST['rand'];
echo $random; ?>
In my browser (Firefox), I'm getting the following error:
Notice: Undefined index: rand in
G:\xampp\htdocs\process.php on line 2
Does anyone know how I can echo the hidden value without using complex techniques?
Thanks in advance,
Maxime

You haven't echoed your rand function within the hidden input tag.
Also, there should be a submit button. Only then you can access the POST parameters.
<input type="hidden" name="rand" value="<?php echo rand(1,10); ?>" />
<input type="submit" name="submit" value="submit">
Try something like this:
if (isset($_POST['submit'])) {
echo "<pre>";
print_r($_POST); // See your POST array
$random = $_POST['rand'];
echo $random;
}
Hope this helps.
Peace! xD

Related

PHP Undefined Variable, but it's defined and has a value

I am working on a PHP project - I had one form post a date to another form
I made some changes (although none to the input in question)
Now all other inputs are updated with their Posted values, except the date
If I manually set the date in HTML it works:
<div><input type="date" class="form-control" id="DateCourse" name="DateCourse" value="2009-01-01"></div>
If I set it to the following, it doesn't:
<div><input type="date" class="form-control" id="DateCourse" name="DateCourse" value="<?php echo (isset($DateCourse))?$DateCourse:'';?>"></div>
The below:
$DateCourse = ($_POST["DateCourse"]);
var_dump($_POST["DateCourse"]);
var_dump($DateCourse);
Returns:
string(10) "2019-01-05" - means the post value is set
Notice: Undefined variable: DateCourse in /home/bitecons/bts.biteconsulting.co.za/v2/editccr.php on line 119 - how can it be undefined, I just defined it
NULL
What on earth am I doing wrong? Apart from using PHP :P
Flow as requested:
Records.php:
This is the function to prepopulate my posted fields:
function Prefill(x) {
TabletoEdit = x.closest('table').id;
SelectedRow = x.rowIndex;
document.getElementById("EntryEditing").value = x.cells[19].innerHTML;
document.getElementById("DateCourse").value = x.cells[0].innerHTML;
document.forms["records"].submit();
}
Then I also have:
<form action="editrec" method="post" id="records">
<input type='hidden' name='Period' id='Period' />
<input type='hidden' name='Month' id='Month' />
<input type='hidden' name='res' id='res' />
<input type='hidden' name='CustName' id='CustName' />
<input type='hidden' name='DateCourse' id='DateCourse' />
</form>
The Prefill gets called, then submits the form
I have tracked and DateCourse has data, but when getting to the other form, it "disappears":
if(!empty($_POST)) {
$DateCourse = ($_POST["DateCourse"]);
$CustName = ($_POST["CustName"]);
}
For example, CustName is filled in, but not DateCourse?
Side question:
Would this return true if another post var is not set (unrelated to this one):
if(!empty($_POST))
I think You use wrong Code
you Must Submit First Form And Then Use $DateCourse this In another Form in POSTBACK
One of the best way is to define $DateCourse too like
<?php
$DateCourse = "";
if(!empty($_POST["DateCourse"])) {
$DateCourse = ($_POST["DateCourse"]);
}
?>
<div><input type="date" class="form-control" id="DateCourse" name="DateCourse" value="<?php echo $DateCourse;?>"></div>
Okay, apologies folks, but it may help others in the future.
I had a function call to an old function - this failed, causing my variable to never get defined... I knew it was something stupid, but sometimes one needs a sound board...

Can't use a form's value in a different php file

Having issues with using a form's value in a different php file:
my firstpage.php
<form method="post">
<input type="radio" name="rdbbtn" value="1"> One
<input type="radio" name="rdbbtn" value="2"> Two
</form>
my secondpage.php is here
<?php
include("firstpage.php");
$result = $_POST['rdbbtn'];
if ($result == "1") {
echo 'thirdpage.php';
}
else {
echo 'fourthpage.php';
}
?>
problem:
Notice: Undefined index: rdbbtn in
how come I can't use "rdbbtn"? Should I have something like
$rdbbtn = $_POST['rdbbtn'];
in secondpage.php? Tried this but didn't solve my problem.
firstpage.php and secondpage.php are in the same directory.
Probably it's some pretty obvious thing that I don't see...thanks!
EDIT: I have accepted pradeep's answer as that helped me the most to figure what the problem should be. would like to say thank you for everybody else showing up here and trying to help!
When you change current page it reset the value and $_POST is empty.
You can try with set form action to next page . It will work
<form method="post" action="secondpage.php">
<input type="radio" name="rdbbtn" value="1"> One
<input type="radio" name="rdbbtn" value="2"> Two
<input type="submit" name="" value="Next">
</form>
Other wise you can make a function in a class and set each page action
to this function.
And set your each form data to session.
Finally when you change the page you read data form session.
Class FormAction{
public function setFormDataToSession(){
if(isset($_POST['rdbbtn']){
$_SESSION['rdbbtn'] = $_POST['rdbbtn'];
}
}
}
In your page simply get the session value.
echo $_SESSION['rdbbtn'];
Should be like this :
Check with isset method in
<?php
include("firstpage.php");
$result = isset($_POST['rdbbtn']) ? $_POST['rdbbtn'] : NULL;
if ($result == 1) {
echo 'thirdpage.php';
}
else {
echo 'fourthpage.php';
}
?>
and your form should be like this :
<form method="post">
<input type="radio" name="rdbbtn" value="1"> One
<input type="radio" name="rdbbtn" value="2"> Two
<input type="submit" name="submit" value="submit">
</form>
Sorry for not being able to comment in this post(less reputations). But seems like you are asking about storing the variables of the session. This way you can use the variables for a whole session. Just start the session by putting session_start() in the very beginning of secondpage.php file and then you can access the variables at any time during the session by simply calling $_SESSION['rdbutton] in any page like fourthpage.php or anything. Just make sure u put the session_start() at the top of each page where you want to use the variables. Don't forget the semicolons at the end. 😜 Hope this helps.

How do I pass an Object between Web Pages through POST in PHP?

Is it possible to pass an Object through a Hidden Field in an HTML Form using $_POST and retrieve that Object on the page that the form links to?
On the first page, I have a form like the one below:
<?php
session_start();
require_once '../Model/player.php'; // To Enable Creation of a New Player Object
$playerName = filter_input(INPUT_POST, 'playerName');
$playerNumber = 1;
$player = new player($playerName, $playerNumber);
if (isset($player))
{
echo '<p>Successfully created your player!</p><br>';
?>
<form class="viewStats" action="../View/displayPlayerStatsView.php" method="post">
<input type="hidden" name="playerObject" value="<?php echo $player; ?>">
<input type="submit" value="View Your Player's Stats">
</form>
<?php
}
?>
And on the second (receiving) page, I have code like the code below:
session_start();
require_once '../Model/player.php'; // To Use Player Object
$player = filter_input(INPUT_POST, 'playerObject'); // ERROR: Thinks the Player Object is a string.
My error seems to be that the receiving page that retrieves the 'playerObject' from the $_POST array is acting like the Object is a string.
Can anyone give me guidance on how to pass an Object from one page to another using the $_POST array? Is this even possible?
Thank you in advance.
UPDATE:
Based on suggestions to serialize the Object, I now am getting the following errors:
If I change my code on the first (sending) page to:
$playerSerial = serialize((object) $player);
<form class="viewStats" action="../View/displayPlayerStatsView.php" method="post">
<input type="hidden" name="playerObject" value="<?php echo $playerSerial; ?>">
<input type="submit" value="View Your Player's Stats">
</form>
and change the code on the second (receiving) page to:
$playerSerial = filter_input(INPUT_POST, 'playerObject');
print_r($playerSerial);
$player = unserialize($playerSerial);
then the output I get from print_r($playerSerial); is O:6:, which I know is incorrect since the object has properties holding a player's name, number, health, strength, etc.
The require_once '../Model/player.php'; code exists in both PHP files, and it comes right at the top of both before any other code is executed.
You have to make a few additions and corrections:
<?php
//... your previous code
$player = serialize($player);
?>
<form class="viewStats" action="../View/displayPlayerStatsView.php" method="post">
<input type="hidden" name="playerObject" value="<?php echo $player; ?>">
<input type="submit" value="View Your Player's Stats">
</form>
Use the serialize() function to create a string that can be passed to your other page which you can unserialize() as follows:
secondPage.php:
$player = $_POST['playerObject'];
$player = unserialize($player);
Also, you forgot to use echo here:
change
value="<?php $player ?>"
to
value="<?php echo $player; ?>"
Get yourself into serialization: the process of making a string from the object, which can in future be deserialized from the string back to object.
Some docs, which could be useful for you:
PHP - How object serialize/unserialize works?
http://php.net/manual/ru/oop4.serialization.php
http://www.phpinternalsbook.com/classes_objects/serialization.html

SESSIONS: using a user input variable for multiple php pages [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 trying to study php and I'm already on the sessions part where I want to input something on my first page that would then be an output for the second page
1stpage.php
<?php session_start();?>
<form method="post">
Enter a number: <input type="number" name="num1" min="1" max="20" value="<?php echo $_SESSION["$num1"];?>">
<a href ="2ndpage.php">
<input type="button" name="select" value="select">
</a>
</form>
2ndpage.php
<?php
session_start();
echo $_SESSION[$num1];
?>
Well, it does'nt work and I'm getting lots of undefined index error. Any fix guys? Thanks in advance.
Take a look at form handling:
http://www.w3schools.com/php/php_forms.asp
If you still want to save the value into a session use:
$_SESSION['num1'] = $_POST['num1'];
1stpage.php
<?php session_start();?>
<?php if(isset($_SESSION['num1'])) $num1 = $_SESSION['num1']; else $num1 = ''; ?>
<form method="post" action="2ndpage.php">
Enter a number: <input type="number" name="num1" min="1" max="20" value="<?php echo $num1;?>">
<input type="submit" name="select" value="select">
</form>
2ndpage.php
<?php
session_start();
$_SESSION['num1'] = $_POST['num1'];
echo $_SESSION['num1'];
?>
What I have done here is I have first looked into the session if the num1 offset has been set into the session. If its not then I give $num as blank else I set the assign the value from session to $num.
Now when we input something and post it on 2nd page, the posted value is assigned to the variable in session and is displayed as well. So that next time you visit 1stpage.php while in same session, you will see your last posted value.
Let us know if it solves your practive problem or if this is not what you wanted.
I believe this is what you're trying to do:
Page 1:
<?php
session_start();
if(isset($_POST['select'])){
$num1 = $_POST['num1'];
$_SESSION['num1'] = $num1;
}
?>
<form method="post">
Enter a number: <input type="number" name="num1" min="1" max="20" value="<?php echo $_SESSION['num1']; ?>">
<input type="submit" name="select" value="select">
Click here to See the Value
</form>
Page 2:
<?php
session_start();
echo $_SESSION['num1'];
?>
Where, at first you press the select to enter the value inside
num1 then click on Click here to See the Value to see it.
I don't think you understand how all this works. You're having PHP output a session variable into a text box and expecting that that text box will somehow magically update your session. Somewhere you have to pass that data back to PHP and update it. So let's make your code into a process
<?php session_start(); ?>
<form method="post" action="process.php">
Enter a number: <input type="number" name="num1" min="1" max="20" value="<?php echo $_SESSION["$num1"];?>">
<input type="submit" name="select" value="select">
</form>
What I've done is make this form do a basic POST. If you want to avoid this you can use AJAX instead (same result using JS instead of HTML)
Next, let's make a basic process.php intermediate page
<?php
session_start();
$_SESSION['num1'] = (int)$_POST['num1'];
header('Location: 2ndpage.php');
Now we have a logistics chain for the data. You accept the data in your HTML and POST it to this page. It then takes it, sanitizes it (note I cast it to an (int) so we are certain this is a number) and then issues a redirect to the browser which takes you to your original landing page, which should now work.
This is all oversimplified for the process of teaching. You could have your form submit directly to 2ndpage.php and process there. Or, as I said before, you could use AJAX to send to process.php and when it returns some success parameter you then use JS to redirect. You have many options here.
Put this on the first page:
$_SESSION['num1'] = $num1;
and this on the second
$num1 = $_SESSION['num1'];

keep adding value in php

Initially,the $number = 0. After 1st time clicking Add button, the value becomes 10. When 2nd time clicking, the value is changed to 20. then 3rd time is 30, 4th time 40.
Below is my code, is there anyone know how to fix it? Thanks!
<?php
$number = 0;
if(isset($_POST['add'])){
$number = $number +10;
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>">
<?php echo $number; ?>
<input type="submit" name="add" value="Add" />
</form>
</body>
</html>
<input type="hidden" value="<?php echo $number ?>" name="number" />
Now change the $_POST['add'] to $_POST['number']
And $number = $_POST['number'] + 10;
This is fundamental to how PHP works.
There is no 'state' in between requests. This means that everything will be forgotten for every request. So if you want to retain data, you have to store it somewhere.
A couple of options:
A database such as MySQL
A session
A cookie
A caching system such as APC
First of all, your PHP needs a little adjusting:
<?php
$number = ($_POST['add'] != '') ? 0 : $_POST['add'];
$number += 10;
?>
<html>
Then add a hidden input above the <input type="submit">, like so:
<input type="hidden" name="add" value="<?php echo $number; ?>">
Use the session variable to retain the value per page request. Simple variable values is destroyed once script finish execution. Session variable will keep the value.
Read more about session
or use the database.
You need to save the value somehow. Either you use a database, like MySql, or you could save the value in a session variable.

Categories