PHP: Array appears to reinitialize - php

I'm trying to make a basic html form that passes information to a php object then adds said object to an array. It works to the point of passing the information from the form, to the object, and adding it to the array and displaying said object. However, when I try to add a second object to the array it only seems to replace the array with a new single element array rather then adding to it. Here is my code... any ideas?
index.php file:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Custom Forms</title>
</head>
<body>
<h2>Add Data</h2>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
First Name:<input type="text" size="12" maxlength="12" name="Fname"><br />
Last Name:<input type="text" size="12" maxlength="36" name="Lname"><br />
<button type="submit" name="submit" value="client">Submit</button>
</form>
<?php
include_once 'clientInfo.php';
include_once 'clientList.php';
if ($_POST) {
$clientArray[] = new clientInfo($_POST["Fname"], $_POST["Lname"]);
}
if (!empty($clientArray)) {
$clientList = new clientList($clientArray);
}
?>
<p>go to client list</p>
</body>
</html>
clintInfo.php file:
<?php
class clientInfo {
private$Fname;
private$Lname;
public function clientInfo($F, $L) {
$this->Fname = $F;
$this->Lname = $L;
}
public function __toString() {
return $this->Fname . " " . $this->Lname;
}
}
?>
clientList.php file:
<?php
class clientList {
public function clientList($array) {
foreach($array as $c) {
echo $c;
}
}
}
?>
EDITED WORKING CODE WITH ANSWER
index.php file:
<?php
include('clientInfo.php');
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Custom Forms</title>
</head>
<body>
<h2>Add Data</h2>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
First Name:<input type="text" size="12" maxlength="12" name="Fname"><br />
Last Name:<input type="text" size="12" maxlength="36" name="Lname"><br />
<button type="submit" name="submit" value="client">Submit</button>
</form>
<?php
if ($_POST) {
$testClient = new clientInfo($_POST["Fname"], $_POST["Lname"]);
echo $testClient . " was successfully made. <br/>";
$_SESSION['clients'][] = $testClient;
echo end($_SESSION['clients']) . " was added.";
}
?>
<p>go to client list</p>
</body>
</html>
clientList.php file:
<?php
include('clientInfo.php');
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>
Accessing session variables
</title>
</head>
<body>
<h1>
Content Page
</h1>
<?php
for ($i = 0; $i < sizeof($_SESSION['clients']); $i++) {
echo $_SESSION['clients'][$i] . " was added. <br/>";
}
?>
<p>return to add data</p>
</body>
</html>
The object file clientInfo.php stayed the same. The objects needed to be stored in a multidimensional $_SESSION array and recalled with a for loop, a foreach loop would not work, unless some one else knows a way to make a foreach loop work, stick to a for. On a side note the $testClient variable could be skipped and just created and placed with in the $_SESSION at the same time, however doing it with the temp variable made it easier to trouble shoot and see how to make it work. Just thought I'd post the working code with the answer supplied by Josh!

You need to add persistance to your array object.
See PHP's $_SESSION.
If you don't store it to memory or disk in between requests, it cannot possibly exist on successive loads. There is a nice tutorial in that link that should get you up and running.
Alternatively, you can store things in a database, for larger needs.

Related

How to pass a Variable through a session

I know there are other posts about this, but I still can't seem to see where the code is incorrect.
I'm trying to pass a variable from one page to another via session: Below are the two pages; excuse some of the variable names as I was just plotting them in quickly.
main.php
<?php
session_start();
session_unset();
if(isset($_POST['submit']))
{
$_SESSION['itemId'] = $_POST['firstName'];
echo "name = " . $_SESSION['itemId'];
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="result.php" method="POST">
First name:
<input type="text" name="firstName" placeholder="First Name">
<br>
<input type="submit" name="submit">
</form>
</body>
</html>
result.php
<?php
session_start();
echo $_SESSION['itemId'];
session_destroy();
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
Previously I didn't have the unset in there. However, it hasn't made a difference.
The value is getting stored in the session, its just not passing it through to the other page.
Main page should looks like this:
<?php
session_start();
//remove session_unset();
if(isset($_POST['submit']))
{
$_SESSION['itemId'] = $_POST['firstName'];
echo "name = " . $_SESSION['itemId'];
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="result.php" method="POST">
First name:
<input type="text" name="firstName" placeholder="First Name">
<br>
<input type="submit" name="submit">
</form>
remove session_unset(); line after start_session()
and why r u destroying session in result page.
if you want to destroy then
store session value in variable
$id = $_SESSION['itemId'];
echo $id;
this code will help u

Why doesn't isset in an if statement work it always passes

It is printing my print statement even though I haven't touched anything on the page. Without having put anything in the number box, or having pushed the submit button it seems to be running anyway, ignoring/passing the if statement.
<!doctype html>
<html>
<head>
<link rel="icon" type="image/ico" href="/favicon/favicon.ico">
</head>
<body style="background-color:black;color:white">
<form name="form1" method="POST" action="bogo.php">
Size
<input type="number" name="size" value="" max="10000" min="1">
<input type="submit" name="submit" value="submit">
</form>
<br/>
<?php
function foo(){
if(isset($_POST["size"]) && isset($_POST["submit"])){
$a = $_POST["size"];
$i = 0;
for($i=0;$i<$a;$i++) {
$arr[$i] = $i;
}
print("Original Array: <br/>");
}
else {
}
}
foo();
?>
</body>
</html>
You need to put php code outside html code.
<html>
</html>
<?php>
php code
<?>

PHP Keep the variable scope even after the page reload

The website generates the random number from 1 to 100 when accessing the first page(page1.php). And the user will guess the number.
The first page contains
- a text box for accepting a
number from the user, and a submit button.
The second page(page2.php) will be returned to the user if the guess number is too high or too low. And the page shows a message telling the user "Too High" or "Too Low". The page also contains
a button(retry button) that allows the user to go back to the first page(page1.php) to re-enter a new number
a button that allows the user to quit the game.
The third page(page3.php) is returned to the user if the guess is correct. The page displays "Correct", the random number, and the count of tries.
And I have this index.php which is heart for all the pages. And here is the code.
index.php
<?php
$name = '';
$inputnumber = '';
$random = 33; //this is just an assumption to keep it simple
$message = '';
$guesscount = '';
if (isset($_POST['action'])) {
$action = $_POST['action'];
}
if ($action === 'guess') {
$guesscount = $_POST['$guesscount'];
$inputnumber = $_POST['$inputnumber'];
if ($inputnumber == $random) {
$message = "Correct!";
include 'page3.php';
}
if ($inputnumber > $random) {
$message = "Too High";
include 'page2.php';
}
if ($inputnumber < $random) {
$message = "Too Low";
include 'page2.php';
}
}
if ($action === 'retry') {
include 'page1.php';
}
page1.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Number Guess: <input type="text" name="$inputnumber" value="<?php if(isset($inputnumber)==1){
echo $inputnumber;}else echo ""; ?>" /><br>
<input type="submit" name="action" value="guess" />
<hr>
Guess Count: <?php echo $guesscount; ?>
</form>
</body>
</html>
page2.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Message: <?php echo $message; ?>
<input type="hidden" name="$guesscount" value="<?php echo $guesscount;?>"/><br>
<input type="submit" name="action" value="retry" />
<hr>
Guess Count: <?php echo $guesscount;?>
</form>
</body>
</html>
page3.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Message: <?php echo $message; ?>
Number of Tries: <?php echo $guesscount; ?>
<input type="submit" name="action" value="ok" />
</form>
</body>
</html>
page1.php is the page to load first.
Challenge I have faced is, I couldn't keep the $guesscount stable always. It keeps resetting on me. I have tried session but couldn't resolve it.Please help resolving it.
Thanks in advance.
I don't know why but my gut feeling tells me that the reason why the session is not working for you on other pages is because you do not initiate it ??
So what you have to do is:
index.php
<?php
session_start();
$_SESSION['myVariable'] = 'myVariable';
?>
page1.php
<?php
session_start();
$mySessionVar = $_SESSION['myVariable'];
var_dump($mySessionVar); // <- this should print myVariable
?>
You may get an error saying that $_SESSION is null or not set and to prevent that you can just enclose $_SESSION inside and isset method
if(isset($_SESSION['myVariable']) && $_SESSION['myVariable'] != null) {
$mySessionVar = $_SESSION['myVariable'[;
}

Response from one page to another page in php without ajax

I am just started with Php and have some doubts.
I created 2 pages one.php and two.php
ONE.php
<body>
<form method="post" action="TWO.php">
First Number<input type="text" name="txt1"><br>
Second Number<input type="text" name="txt2"><br>
<input type="submit">
</form>
</body>
TWO.php
<body>
<?php
$sum=$_POST["txt1"] + $_POST["txt2"];
echo $sum;
?>
</body>
I POST values form one.php to two.php. Two.php calculates the sum and echo's the result.
My query is would I be able to get the sum echoed on one.php using just php and its important to post the data on another page and get the response from there.
Yes you are. Simply, handle the form submission (the POST request) in one.php. When the request for one.php is not POST just show the form.
The typical way is:
// ONE.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$content = "Sum is " . $_POST["txt1"] + $_POST["txt2"];
}
else {
$content = <<<EOC
<form method="post" action="ONE.php">
First Number<input type="text" name="txt1"><br>
Second Number<input type="text" name="txt2"><br>
<input type="submit">
</form>
EOC;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>ONE</title>
<meta charset="utf-8"> <!-- or whatever charset you are using -->
</head>
<body>
<?php echo $content ?>
</body>
</html>
Edited, the OP needs the two files but print the result on one.php
In order to pass data between two files you can:
Set the data in the first file (two.php) and require the second (one.php, where you would print the value)
Use PHP sessions.
With the latter you need to do a (well you don't need to but it's mean to work with a) page redirect, so my recommended approach for this case is use the former. The code could be something like:
// TWO.php
<?php
// you should probably check if $_POST['txt1'] and $_POST['txt2'] does really exists and throw and error if not...
$sum = $_POST["txt1"] + $_POST["txt2"];
require "ONE.php" // careful if you're on a *nix file system the NameCase is extremely important!
// ONE.php
<?php
if (isset($sum)) {
$content = "Sum is " . $sum;
}
else {
$content = <<<EOC
<form method="post" action="TWO.php">
First Number<input type="text" name="txt1"><br>
Second Number<input type="text" name="txt2"><br>
<input type="submit">
</form>
EOC;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>ONE</title>
<meta charset="utf-8"> <!-- or whatever charset you are using -->
</head>
<body>
<?php echo $content ?>
</body>
</html>
Try this code:
<body>
<?php
if($_POST){
$sum = $_POST["txt1"] + $_POST["txt2"];
echo $sum;
}else{
?>
<form method="post" action="">
First Number<input type="text" name="txt1"><br />
Second Number<input type="text" name="txt2"><br />
<input type="submit">
</form>
<?php } ?>
</body>
You can try with this, in only one page:
ONE.php
<html>
<head></head>
<body>
<form method="post" action="ONE.php">
First Number<input type="text" name="txt1"><br>
Second Number<input type="text" name="txt2"><br>
<input type="submit">
</form>
<?php
// Verify if $_POST["txt1"] and $_POST["txt1"] are defined
// (when form is submit $_POST, $_GET and other $_ PHP vars
// are set). If form isn't submitted, set 0 on each variable
// to perform sum. Is necessary check values to avoid PHP
// Warnings/Errors (In this case with isset function. There
// are many different ways to perform it)
$txt1 = isset($_POST["txt1"]) ? $_POST["txt1"] : 0;
$txt2 = isset($_POST["txt2"]) ? $_POST["txt2"] : 0;
$sum = $txt1 + $txt2;
//Print sum result
echo 'Sum is: '.$sum;
?>
</body>
</html>
For comparations I'm using ternary operators, that simplify/minimize code of traditional if/else. Also you can use traditional if/else (simple compare) or switch(multiple compare)

POST variable doesn't echo in function

I am currently learning the most basic PHP ever. I have 5 files.
index.php:
<html>
<head>
<title>Budget Calcule</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h2>Put in your: - </h2>
<form action="functions.php" method="post">
<h3>Income</h3>
<label>Salary: <input name="salary" type="text" /></label><br />
<h3>Outgoings</h3>
<label>Living: <input name="living" type="text" /></label><br />
<label>Insurance: <input name="insurance" type="text" /></label><br />
<label>Communication: <input name="communication" type="text" /></label><br />
<label>Loan: <input name="loan" type="text" /></label><br />
<label>Food & Drink: <input name="foodAndDrink" type="text" /></label><br />
<label>Entertaintment / Shopping: <input name="entertainmentOrShopping" type="text" /></label><br />
<label>Transport: <input name="transport" type="text" /></label><br />
<label>Other: <input name="other" type="text" /></label><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
this is my functions.php:
<?php
include('variables.php');
if(!($_POST['Submit'])){
if(isset($_POST['salary'])){
header('Location: output.php');
return $_POST['lon'];
}else{
echo "All fields are required";
}
}
?>
this is my variables.php:
<?php
$salary= $_POST['salary'];
$living= $_POST['living'];
$insurance= $_POST['insurance'];
$communication = $_POST['communication'];
$loan = $_POST['loan'];
$food = $_POST['food'];
$entertaintmentOrShopping = $_POST['entertaintmentOrShopping'];
$transport = $_POST['transport'];
$other= $_POST['other'];
?>
this is my output.php file:
<?php
include('outputFunction.php');
?>
<html>
<head>
<title>Output.php</title>
</head>
<body>
<?php myText(); ?>
</body>
</html>
and last but not least, this is my outputFunction.php file:
<?php
include('variables.php');
function myText(){
echo "Your salary per month is: " . $_POST['salary'];
}
?>
Now you're thinking "why have he split up his code in different files?" Well first of all, I split the variables from functions.php because I wanted outputFunctions.php to get the variables from variables.php so i could echo my `$_POST['salary']; . The function myText(); outputs the text just fine, but it doesnt output the $_POST['salary'];.
I do not know why it doesnt work, I just wonder if you could be my extra eyes and see if I've done some mistake.
PS! Don't down vote my question just because you think it's stupid. I am having problem with this issue and been working on it for hours without advancing anywhere.
A few things:
You don't need to include a variables.php file. The variables you're accessing are global and you're just creating duplicates that aren't being used. They also go away after the page changes since you're re-declaring them each page load.
You are also trying to call a variable that doesn't exist when you reference $_POST['lon'] instead of 'loan'.
And finally to actually answer your question:
Your myText() function is referencing a variable that is not there anymore.
You need to merge functions.php and outputFunction.php and output.php into one file so the variables aren't lost and all the processing is done without opening a new file each time. I can see your original concept for separated files but an output file is going to be the file to process the input data from the form.
Now in your newly merged output.php, you should have something resembling this:
<html>
<head>
<title>Output</title>
</head>
<body>
<?php
if(isset($_POST['Submit'])) {
if(isset($_POST['salary'])) {
echo "Your salary per month is: " . $_POST['salary'];
}
} else {
echo "All fields required.";
}
?>
</body>
</html>
This means only two files - your form page and this page.
A few more tips:
If you want to check if the form was submitted, it has look something like this:
if(isset($_POST['Submit'])){ ... }
Also, you should add a name="" attribute to your submit-Button:
<input type="submit" name="Submit" value="Submit" />
And what is the variables.php for? You don't use any of those variables.
When you redirect the user via header() the data that is stored in the $_POST array gets lost.
You could directly redirect to ouput.php
<form action="output.php" method="post">
And do something like this:
<?php
include('outputFunction.php');
if(isset($_POST['Submit'])) {
if(isset($_POST['salary'])) {
?>
<html>
<head>
<title>Output.php</title>
</head>
<body>
<?php myText(); ?>
</body>
</html>
<?php
} else {
echo "All field required";
}
}
?>
By the way you can always check what your $_POST contains with print_r($_POST);
This can be very useful for debugging.

Categories