First element in array keeps getting overwritten, will not add onto array - php

I am trying to create a quiz, in order to do this I am using a form which users will input information into, once they submit this form it should add the input to an array/list.
The user should then be able to enter information and the process would repeat.
The finished product would be an array with each element corresponding to the order the answers were given.
-
I have tried so far using both array_push() and declaring elements, eg: $my_array[0] = $input;.
The current problem I am experiencing is that each time I submit the form, the $count variable doesn't seem to increment.
Instead it simply stores the data in the first element and overwrites which was previously there.
I am inclined to believe this is a problem with the posting of the submit button.
-
Here is my code:
<html>
<body>
<form action="" method="POST">
<input type="text" name="INPUT" placeholder="Input something"; required /><br><br>
<input type="submit" name="Submit" /><br><br>
<?PHP
$my_array = array();
$count = 0;
if(isset($_POST['Submit'])){
global $count;
$input = $_POST['INPUT'];
$my_array[$count] = $input;
print_r($my_array);
echo "Count:" . $count;
$count++;
}
?>
</form>
</body>
</html>

The crux of the issue here is that variable values do not persist across PHP requests. Every time you submit the form, you are throwing away your old $count and $my_array variables and initializing new variables with the same names.
Here is a working version of your code snippet, which takes advantage of the PHP $_SESSION variable to have persistent information between requests:
<?php
session_start();
if (!isset($_SESSION["my_array"])) {
$_SESSION["my_array"] = array();
}
?>
<html>
<body>
<form action="" method="POST">
<input type="text" name="INPUT" placeholder="Input something"; required /><br><br>
<input type="submit" name="Submit" /><br><br>
<?php
if(isset($_POST['Submit'])){
array_push($_SESSION["my_array"], $_POST['INPUT']);
print_r($_SESSION["my_array"]);
echo "Count:" . count($_SESSION["my_array"]);
}
?>
</form>
</body>
</html>

Related

Form Inputs and PHP

Need a little help with my coding. I'm working on a project in which it will accept 5 different numbers and insert them into a PHP array. The codes I have tried are written below. Both of them would make all the 5 contents of my array the same number, appreciate a little help please? Never dealt with array in PHP yet.
<form action="activity_1.php" method="post">
<input type="text" name="number">
<input type="submit" value="Submit" name="submit">
</form>
So far these are the ones I've tried:
$no = array();
for($i=1; $i<=5; $i++){
array_push($no, $_POST['number']);
}
Also
$no = array();
for($i=1; $i<=5; $i++){
//$no[$i]= $_POST['number'];
}
You may use one session variable to store the posted data.
So slightly amend your code into the following :
<?php session_start(); ?>
<form action="#" method="post">
<input type="text" name="number">
<input type="submit" value="Submit" name="submit">
</form>
<?php
if ( !isset($_SESSION["no"]) ) {
$_SESSION["no"]=array();
}
if (isset($_POST["number"])){
array_push($_SESSION["no"], $_POST['number']);
}
for($i=0; $i<5; $i++){
if (isset($_SESSION["no"][$i])) {
if ($_SESSION["no"][$i]!="") {
echo " Number you entered was: " .$_SESSION["no"][$i] . "<br>";
}
}
}
?>
In my opinion the code can be further amended so that
a) you should have a button to "clear" all the previous entered number;
b) I don't know whether it is necessary, but you may wish to add a function to check whether a newly entered number is the same as one of the past numbers entered, and if they are the same, do not put it into the array.

i want to be able to echo all the element in an array?

I pretty newbie to php and javascript but more i am curious about PHP. I want to add elements into a empty array every time i add a new element trough a input form, and after that i want those elements to be displayed in to the browser .The code i use is this
<form action="index.php" method="POST">
<input type="text" name="name" placeholder="name"><br><br>
<input type="submit" name="submit" value="enter"><br><br>
</form>
<?php
if (isset($_POST['submit'])) {
$_SESSION['names']=array();
$names=$_SESSION['names'];
$name=$_POST['name'];
array_push($names,$name);
for($i=0;$i<count($names);$i++){
echo $names[$i];
}
};
How could i achieve to display every element inside the array that i add trough the input field in php?
You overwrite the value every time because you wipe out the array on every page load: $_SESSION['names']=array();. Instead check to see if that session variable exists (and is an array) first and, if it doesn't, then create it. Otherwise just append to that array.
<form action="index.php" method="POST">
<input type="text" name="name" placeholder="name"><br><br>
<input type="submit" name="submit" value="enter"><br><br>
</form>
<?php
session_start();
if (isset($_POST['submit'])) {
if (!isset($_SESSION['names']) || !is_array($_SESSION['names'])) {
$_SESSION['names'] = array();
}
$name = $_POST['name'];
$_SESSION['names'][] = $name;
$num_names = count($_SESSION['names']);
for($i=0;$i<$num_names;$i++){
echo $_SESSION['names'][$i];
}
};

How to put an input value into the array multiple times and remember it?

Is there any solution for this? Sorry if I didn't explain this good.
When I put some value in $_POST['name'] and submit form I want to put that value in array( $arr ) and when I put some diferent value second time in $_POST['name'] and submit form I want that value put in array ( $arr ) to. Now that array should have two element ( first value and second value from $_POST['name'] )
<?php
session_start();
$_SESSION['name'] = 1;
$arr =array();
if(isset($_POST['submit']) && trim($_POST['name']) != '') {
$arr[] = $_POST['name'];
}
print_r($arr);
?>
<form action="" method="post">
<input type="text" name="name" value="" />
<input type="submit" name="submit" value="Submit" />
</form>
I started session, chacked if is form submitted and if is an empty field.
I tried with hidden input with value of $token = rand(); adn it not worked.
This should be easy, but I have some trouble do fix it.Tnx!
PHP is a stateless language and doesn't store variables from one page load to another. Each time you are submitting the form the $arr variable is destroyed from memory when the page has been processed.
If you want to keep information across page loads then you need to store it in the super global variable $_SESSION as a key value pair.
If you use the modified code below it will store the value typed into the name input when the form is posted in a two level multidimensional array that can be accessed using $_SESSION['name'] and a numeric index.
<?php
session_start();
if(isset($_SESSION['name']) && !is_array($_SESSION['name']))
{
$_SESSION['name'] = array();
}
if(isset($_POST['submit']) && trim($_POST['name']) != '') {
$_SESSION['name'][] = $_POST['name'];
}
print_r($_SESSION);
?>
<form action="" method="post">
<input type="text" name="name" value="" />
<input type="submit" name="submit" value="Submit" />
</form>

Accumulate multiple POSTs

I'm using autocomplete search in my project where user inputs an integer, submits it and it shows in same page what integer was passed in. I want users to be able - after submitting first integer - to submit another one, just can't figure out the solution. My code:
<form action='' method='post'>
<p>Add integrent:</p><input type='text' name='sastavdalja'value=''class='auto'>
<input type="submit" name="submit" value="Submit" />
<br/>
<p>Added integrents</p>
<?php
$int = $_POST["sastavdalja"];
echo $int;
Put this at the top of the page before any output or html
<?php session_start();?>
then use this:
<?php
$_SESSION['int'][]=$_POST["sastavdalja"];
foreach($_SESSION['int'] as $int){
echo $int;
}
Now you're saving each time the user posts something into a session array, and then you're looping through this array and printing each entry in it.

Searching for Array Key in $_POST, PHP

I am trying to add commenting like StackOverflow and Facebook uses to a site I'm building. Basically, each parent post will have its own child comments. I plan to implement the front-end with jQuery Ajax but I'm struggling with how to best tackle the PHP back-end.
Since having the same name and ID for each form field would cause validation errors (and then some, probably), I added the parent post's ID to each form field. Fields that will be passed are commentID, commentBody, commentAuthor - with the ID added they will be commentTitle-12, etc.
Since the $_POST array_key will be different each time a new post is processed, I need to trim off the -12 (or whatever the ID may be) from the $_POST key, leaving just commentTitle, commentBody, etc. and its associated value.
Example
$_POST['commentTitle-12']; //how it would be received after submission
$_POST['commentTitle']; //this is what I am aiming for
Many thanks
SOLUTION
Thanks to CFreak-
//Basic example, not actual script
<?php
if (array_key_exists("send", $_POST)) {
$title = $_POST['title'][0];
$body = $_POST['body'][0];
echo $title . ', ' . $body;
}
?>
<html>
<body>
<form name="test" id="test" method="post" action="">
<input type="text" name="title[]"/>
<input type="text" name="body[]"/>
<input type="submit" name="send" id="send"/>
</form>
</body>
</html>
Update 2
Oops, kind of forgot the whole point of it - unique names (although it's been established that 1) this isn't really necessary and 2) probably better, for this application, to do this using jQuery instead)
//Basic example, not actual script
<?php
if (array_key_exists("send", $_POST)) {
$id = $_POST['id'];
$title = $_POST['title'][$id];
$body = $_POST['body'][$id];
echo $title . ', ' . $body;
}
?>
<html>
<body>
<form name="test" id="test" method="post" action="">
<input type="text" name="title[<?php echo $row['id'];?>]"/>
<input type="text" name="body[<?php echo $row['id'];?>]"/>
<input type="hidden" name="id" value="<?php echo $row['id']; //the ID?>"/>
<input type="submit" name="send" id="send"/>
</form>
</body>
</html>
PHP has a little trick to get arrays or even multi-dimensional arrays out of an HTML form. In the HTML name your field like this:
<input type="text" name="commentTitle[12]" value="(whatever default value)" />
(you can use variables or whatever to put in the "12" if that's what you're doing, the key is the [ ] brackets.
Then in PHP you'll get:
$_POST['commentTitle'][12]
You could then just loop through the comments and grabbing each by the index ID.
You can also just leave it as empty square brackets in the HTML:
<input type="text" name="commentTitle[]" value="(whatever default value)" />
That will just make it an indexed array starting at 0, if you don't care what the actual ID value is.
Hope that helps.
You just have to iterate through $_POST and search for matching keys:
function extract_vars_from_post($arr) {
$result = array();
foreach ($arr as $key => $val) {
// $key looks like asdasd-12
if (preg_match('/([a-z]+)-\d+/', $key, $match)) {
$result[$match[1]] = $val;
} else {
$result[$key] = $val;
}
}
return $result;
}
Didn't test the code, though

Categories