Array push with $_SESSION and $_POST not working - php

So I'm kind of new to PHP, otherwise I wouldn't be here I guess.
Anyway, I've been trying to practice, and I'm currently building a Shoutbox.
However, I can't seem to save anything other than the previous shout. They seem to keep replacing each other at the first entry of the array. I tried everything I could think of, and it might be something I did with the HTML form name, but I'm clueless.
So, here goes, I hope someone has a lightbulb moment when looking at it.
This is the PHP:
session_start();
$_SESSION['shout'] = array();
array_push($_SESSION['shout'], $_POST['shout'][0]);
$arrayPlace = count($_SESSION['shout']);
foreach($_SESSION['shout'] as $key => $value)
{
$arrayPlace+=1;
echo $arrayPlace;
}
?>
And the HTML:
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<h2>Shoutbox Kevin</h2>
<label for="text">Vul hier uw Shout! in:</label></br>
<input type="text" name="shout[]"/></br>
<input type="submit" value="Verzenden" />
</form>

The problem is: every time you post a shout, you re-initialize the shout-array:
$_SESSION['shout'] = array();
You shoud do that only once (if it doesn't exists):
if (!isset($_SESSION['shout'])) {
$_SESSION['shout'] = array();
}
BTW: You can leave both the [0] in $_POST['shout'][0] and the [] in name="shout[]" away if you let users only shout one message at a time.

Related

How to save POST data of a form after user submission without using Sessions, JSON, Ajax, Hidden input or another file

First of all I'll be sincere, I'm a student and I've been asked to do a task that seems impossible to me. I don't like asking questions because generally speaking I've always been able to fix my coding issues just by searching and learning, but this is the first time I've ever been on this possition.
I need to create a php file that contains a form with two inputs that the user fills. Once he clicks submit the website will show on top of it the two values. Till here I haven't had an issue, but here's the problem, the next time the user sends another submission, instead of clearing the last 2 values and showing 2 new ones, now there needs to be 4 values showing.
I know this is possible to do through JSON, the use of sessions, Ajax, hidden inputs or using another file (this last one is what I would decide to use if I could), but the teacher says we gotta do it on the same html file without the use of any of the methods listed earlier. He says it can be done through an Array that stores the data, but as I'll show in my example, when I do that the moment the user clicks submit the array values are erased and created from zero. I know the most logical thing to do is asking him, but I've already done that 4 times and he literally refuses to help me, so I really don't know what to do, other than asking here. I should point out that the answer has to be server side, because the subject is "Server-Side Programming".
Thank you for your help and sorry beforehand because I'm sure this will end up being a stupid question that can be easily answered.
For the sake of simplicity I erased everything that has to do with formatting. This is the code:
<?php
if (isset($_POST['activity']) && isset($_POST['time'])){
$agenda = array();
$activity = $_POST['activity'];
$time = $_POST['time'];
$text = $activity." ".$time;
array_push($agenda, $text);
foreach ($agenda as $arrayData){
print implode('", "', $agenda);
}
}
?>
<html>
<head>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<label for="Activity">Activity</label><br>
<input name= "activity" type="text"><br><br>
<label for="Time">Time</label><br>
<input name= "time" type="time"><br><br>
<input type="submit">
</form>
</body>
</html>
Your question was not very clear to be honest but I might have gotten something going for you.
<?php
$formaction = $_SERVER['PHP_SELF'];
if (isset($_POST['activity']) && isset($_POST['time'])){
$agenda = array();
//if the parameter was passed in the action url
if(isset($_GET['agenda'])) {
$agenda = explode(", ", $_GET['agenda']);
}
//set activity time
$text = $_POST['activity']." ".$_POST['time'];
//push into existing array the new values
array_push($agenda, $text);
//print everything
print implode(", ", $agenda);
//update the form action variable
$formaction = $_SERVER['PHP_SELF'] . "?agenda=" . implode(", ", $agenda);
}
?>
<html>
<head>
</head>
<body>
<form action="<?php echo $formaction; ?>" method="POST">
<label for="Activity">Activity</label><br>
<input name= "activity" type="text"><br><br>
<label for="Time">Time</label><br>
<input name= "time" type="time"><br><br>
<input type="submit">
</form>
</body>
</html>
SUMMARY
Since you cant save the posted values into SESSION vars or HIDDEN input, the next best thing would be to append the previous results of the posted form into the form's action url.
When the form is posted, we verify if the query string agenda exists, if it does we explode it into an array called $agenda. We then concatenate the $_POST['activity'] and $_POST['time'] values and push it to the $agenda array. We then PRINT the array $agenda and update the $formaction variable to contain the new values that were added to the array.
In the HTML section we then set the <form action="" to be <form action="<?php echo $formaction; ?>

How can we process a dynamic form in php

The newbie is back with another question. Any help would be much appreciated. Suppose we have got a form in which we have written down the name of a user and in front of which there is an input box in which we can allocate a grade to the mentioned user. Within this scenario, everything is clear. We have a form with the name of user (it's 'id' as the value) and another variable, that is the grade' which are posted to the php-action-page. Hence, in the php-action-page, I get two variables, one is the id of the user and the other allocated grade, through POST. Here, everything is clear and the process easy, since I have got just two defined variables. Now, suppose that we are inserting a list of users from our 'Users' table into the form dynamically. We fill our form with for example 10 users grabbed from the database. In front of them there are input boxes for the 'grade' to be inserted into. So far, everything is fine. The problem, though, lies in the next stage. The problem is I don't know how to ask php-action-page to do the insert, that is insert the grade in the database for specific users as long as there are posted variables of users. Here I have tens of users and tens of dynamic variables. And if the question is a little bit vague, please do excuse me; yet, do your best to get me free from this condition of bafflement. Many thanks.
Here comes some bits of the code to make the problem a little more clear.
I start with the following code:
<?php
require_once ('../inc/takein.php');
$pd = new dbase();
$students = $pd->run_a_query('SELECT * from `checking`');
Here I am including the database and other necessary files. Then I run a query to fetch a list of my students from the table. So far, everything is fine. The next line of action which makes me perplexed is the following code.
Before having a look at the code may you please look at the html design in the following picture:
Final Design
I totally have no idea about it being wrong or correct. You might help with this bit as well.
<form action="grades.php" method="post">
<table class="table table-bordered font-label" id="item_table">
<?php
foreach ($students as $student) {
echo '<tr>';
echo '<td>'.$student['name'].'</td>';
echo '<td><input type="text" name="grade[]" class="form-control omit-radius-input"></td>';
echo '<input type="hidden" name="id[]" value="'.$student['id'].'">';
echo '<tr>';
}
?>
</table>
<input type="submit" name="dispatched" class="btn btn-green">
</form>
Here, I am putting the information in a table within the form element. As you can see in the above picture, I am getting four students from the database. Now I want to send these students back to the database along with their newly set grades. What I want to be posted here is the student id and their grades.
Then, the following is the last part of the code which is left incomplete because I couldn't make any senses how to do it.
if (isset($_POST['dispatched'])) {
$id[] = $_POST['id'];
$grade[] = $_POST['grade'];
// what to do now???!!!
foreach(...HOW TO DO THE 'FOREACH') {
...
}
}
May you please help me insert my student grades. Many thanks in advance.
Simply name your variables as arrays - if your form looks like this
<form method="POST">
<input type="text" name="grade[12]">
<br>
<input type="text" name="grade[15]">
<br>
<input type="text" name="grade[7]">
<br>
<input type="text" name="grade[21]">
<!-- continue here -->
</form>
then in your PHP code you will access the grades like this
if(is_array($_POST['grade'])) foreach($_POST['grade'] as $id => $value)
{
// REPLACE INTO user_grades(user_id, grade) VALUES($id, $value)
}
UPDATE
You should also put the ID of your students in the name of the INPUT field - otherwise you won't know for which student is the given grade.
<?php
foreach ($students as $student) {
echo '<tr>';
echo '<td>'.$student['name'].'</td>';
echo '<td><input type="text" name="grade['.$student['id'].']" class="form-control omit-radius-input" value="'.$student['current_grade'].'"></td>';
echo '<tr>';
}
?>
The foreach is shown above in my original answer.

Array and loop PHP

I'm really new new to php. I consider myself alright at Java, but wanted to get more into web stuff. I like HTML and CSS well enough, but I'm having a lot of trouble with php.
I'm writing a really basic php code. I want it to get info from a user (via form) and add it to an array in php (POST). I then would like to store the array as a session variable and write a for loop that prints out each index in an HTML list.
ISSUES:
1. I don't have a good handle on SESSION, so not sure how to store the array as a session variable.
2. I'm not sure how to reference a specific index of an array in php. I've sorta done it in a java way here, but that needs to change.
--CODE--
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
<?php
$stack = array("");
array_push($stack, $_POST[name]);
for(i < $stack.length){
print_r($stack[i]);
}
?>
To access session variables is easy:
First, you need to call the method session_start() (Make sure, you call it, before sending any HTTP header).
After calling the session_start() method, you will have access to the $_SESSION associative array. You will be able to append anything to this array.
The syntax of the for loop in PHP is as follows:
foreach (array_expression as $value)
statement
or
foreach (array_expression as $key => $value)
statement
I hope that it helps.
First let's see the lines of code in PHP you have written:
I.
$stack = array("");
This creates an array called $stack with a single element of "". $stack[0] will have the value of "". You can name the elements of an associated array, like this:
$stack = array("name" => "value");
In this case $stack["name"] will be "value".
II.
array_push($stack, $_POST[name]);
This is incorrect, since name is not a variable, nor a string. You probably meant:
array_push($stack, $_POST["name"]);
this would have written $_POST["name"] at the end of your array having "", so $stack[1] would have been whatever the value of $_POST["name"]; was.
III.
for(i < $stack.length){
This is incorrect syntax. You have meant
for($i = 0; $i < count($stack); $i++){
Note how $ is put in front of all variables and how similar this for cycle is to a Java for.
IV.
print_r($stack[i]);
Incorrect, you need the the cash ($), otherwise your variables will not cooperate.
print_r($stack[$i]);
You, however, do not check whether this is a POST request or a GET. When the user loads the page, it will be a GET request and when he submits the form, it will be a POST request. The first (GET) request will not have $_POST members ($_POST will be empty), as the form was not submitted yet. And if you check whether it is a POST request, you need to check whether "name" is present in $_POST:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') { //it is a post
if (isset($_POST["name"])) { //name is found inside $_POST
echo "Name is " . $_POST["name"];
}
}
?>
Question1:
$_SESSION is an array, like $stack. You can do something like this:
$_SESSION["name"] = $_POST["name"];
This will create a new element of $_SESSION with the index of "name", however, before such an assignment, you need to make sure the session was started.
Question2:
You reference it by the name of the index, just like in Java, however, in PHP you can have textual indexes as well if you want, while in Java you can only use integers.
Just to quickly update the code you have, to make it somewhat workable:
Html code
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
Php code
<?php
$stack = array("");
if(isset($_POST['name'])){
array_push($stack, $_POST['name']);
for($i=0; $i < count($stack); $i++){
echo($stack[$i]);
}
}
?>
Assuming this is all in welcome.php.

get input from html form in PHP by iterations

I am creating a webpage which display a form with 16 questions, each row of input looks like:
<li>*question 1*</li>
<input type="text" name="answer1" style="height: 40px;" size="50" dir="rtl">
<li>*question 2*</li>
<input type="text" name="answer2" style="height: 40px;" size="50" dir="rtl">
and so on - i have 16 (html) lines like that
(by the way, is there a way to prevent this code duplication? this code smells...) and in the end a 'submit' button.
my php script should receive these answers, and put every answer in a variable called "answer(i)" e.g I can write 16 lines of this kind:
if (isset($_POST['submit'])) {
$answer1 = $_POST['answer1'];
$answer2 = $_POST['answer2'];
...ect.
...
}
this (also) feels like a lot of code duplication. is there a way to make it more general and efficient so that if i'm looking to add some new question I won't have to goo through all this again?
I am new to PHP and HTML, and I though of declaring some functions and call them everytime but when I googled keywords like 'html functions' etc. I didn't find and helping info.
edit: The answers labels maybe different than 'answer1, answer2...' and can be a set of different words ('age', 'gender'...)
For the HTML use something like this:
$questions = array(
'question1',
'question2',
//...
);
foreach($question as $id => $qText){
?>
<li>
<?php echo $qText ?>
<input type="text" name="answers[]" style="height: 40px;" size="50" dir="rtl">
</li>
<?php
}
On PHP side you would have your answers in $_POST['answers'], it would be an array. And believe me, if you want to put this values from array into separate variables, it is a red flag: something wrong with your code. You do not want to have a set of answers as independent variables.
You could run a loop to go through the POST array and extract the information into another array.
foreach ($_POST as $k => $v) {
$$k = $v;
}
That will put all of the $_POST data into PHP variables named the same as the form fields generating them (beware you will also get a $submit as well from the button triggering the form).
Is this what you are looking for?
foreach (range(0,16) as $i)
{
${'answer'.$i} = $_POST['answer'.$i];
}
or use extract(), If you apply on your $_POST, keys in your $_POST variable gets assigned as variable.
Here is official documentation.

how to add input to a variable?

I have this form
<form action="process.php" method="post">
Team Name: <input type="text" name="teamname" />
<input type="submit" />
</form>
and this is my php code
$teamname = $_POST['teamname'];
$namelist = "Lakers";
so let's say two people have submitted their team names as Spurs and Rangers
so how do I make the namelist like this and grow as more people submit their team names..
$namelist = "Lakers, Spurs, Rangers";
I have done it in array_push with arrays, but technically i can't call them.
you need to save the names to file/database.
variable save in the memory of the machine and deleted after the scripts done.
$names = array(); // empty array
$names[] = $_POST['teamname']; // add the $_POST['teamname'] to the array
var_dump($names); // prints the names array.
// now the script done, and all the data in the variables will flush from the memory.
You can use array to solve this issue
<?php
$teamname = $_POST['teamname'];
$namelist = $array("Lakers");
array_push($namelist,$teamname);
print_r($namelist);
?>
using database is a simple solution.
but if you still not like to use database in this situation, you can save the variables as a session or cookie variable. it will remain after page refresh.

Categories