PHP Session Array Duplicating - php

I'm trying to set a session array with some pre-defined values, which the user can then add to using a simple html form. My problem is that on the page where the array is set, any refresh or revisit of the page just duplicates the pre-defined values within the array. Not only that, but it also overwrites the value coming from the form each time at the end.
So in this basic example, I have a list of animals and a user can add another animal to the list. But this outputs the pre-defined animals again each time i.e. if I submit the form twice (e.g. adding chicken and then dog) I get the output:
Array ( [0] => pig[1] => cow[2] => sheep[3] => chicken[4] => pig[5] => cow[6] => sheep[7] => dog)
What I want is:
Array ( [0] => pig[1] => cow[2] => sheep[3] => chicken[4] => dog[5])
What am I doing wrong?
index.php
<?php
session_start();
//pre-defined list of animals
$_SESSION['animals'][] = 'pig';
$_SESSION['animals'][] = 'cow';
$_SESSION['animals'][] = 'sheep';
?>
<!--form to add another animal-->
<form action="go.php" method="POST">
<p><input type="text" name="entry1"></p>
<p><input type="submit" name="submit"></p>
</form>
go.php
<?php
session_start();
//add form entry1 to the session array
$_SESSION['animals'][] = $_POST['entry1'];
//print session array
print_r($_SESSION['animals']);
?>

Only initialize the session variable if it's not already set:
if (!isset($_SESSION['animals'])) {
$_SESSION['animals'] = array('pig', 'cow', 'sheep');
}

Check
in_array('YOUR_VALUE',$_SESSION['animals'])
before re inserting it to avoid duplication.
Reference: in_array

I would suggest to not insert data in the session directly, but adding hidden input values like:
<input type=hidden name=extraValue[] value="pig">
<input type=hidden name=extraValue[] value="cow">
etc
In your PHP page, unset the previous session since you want a 'fresh' dataset based on the input, not on the old values.
unset($_SESSION['animals']);
You can access your extra values in $_POST['extraValue']. You then could merge both arrays like
$postValues = array_merge($_POST['extraValue'], $_POST['entry1']);
I havent tested this code yet, but I would use this 'way', rather than setting SESSION values before input.

Related

Changing value inside array to be editable input field

have a small problem. In this part of code:
<?php
$data = [
"eCheckDetails"=>[
"paymentsReceived"=>$history["transactionSummary"]["eCheckTotal"],
"revenueReported"=>$history["transactionSummary"]["eCheckTotal"],
"fundsDeposited"=>$history["transactionSummary"]["eCheckTotal"],
"accountAdjustment"=>0.00],
"paymentCardDetails"=>[
"paymentsReceived"=> $history["transactionSummary"]["paymentCardTotal"],
"revenueReported"=> $history["transactionSummary"]["paymentCardTotal"],
"fundsDeposited"=> $history["transactionSummary"]["paymentCardTotal"],
"accountAdjustment"=>0]
];
data " $history [...][...]"
is taken from another file or database (its not really important from where)
Point is, that this data is sometimes incorrect, and needs to be changed manually. And this is my question. How to make this fields (where $history [..] [..] is) editable, to be
<input type="text">
(with small button ACCEPT or smg somewhere aside) with default value hidden under $history[..][..].
I tried to do it, but its inside array and didnt have any luck. Maybe someone knows?
Best regards
You can use named keys in your HTML attributes, for example <input ... name="history[transactionSummary][eCheckTotal]">. Submitting this back to the server will fill your array.
<?php
$form = <<<EOS
<form method="post" action="">
<input type="text" value="" name="history[transactionSummary][eCheckTotal]">
</form>
EOS;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
var_dump($_POST);
} else {
echo $form;
}
The content of the $_POST superglobal will be:
Array
(
[history] => Array
(
[transactionSummary] => Array
(
[eCheckTotal] => dsdsa
)
)
)

How to give $_SESSION value based on what visitor does in PHP?

I'm having this nasty problem that I can't find an answer to. Basically I have multiple forms on my php page. I need to pass $_SESSION value based on which form visitor uses.
For example, if he uses one form, I need these values
session_start();
$_SESSION['socnetwork'] = '1';
$_SESSION['cost'] = '15';
$_SESSION['soccount'] = '100';
If he uses another form on that page, I need different values to be passed on submit="somepage.php", for example
session_start();
$_SESSION['socnetwork'] = '2';
$_SESSION['cost'] = '55';
$_SESSION['soccount'] = '700';
How would you recommend me to approach this? Variables need to be secure! I cannot pass them in URL, although this would be so convinient.
On the client-side, you may use an if statement (you would need JavaScript in this case) and send the required information to PHP server-side using a POST request.
On the server-side, you may create a handling code, which will set the required values to the $_SESSION variable.
Alternatively, if the values are fixed, you could send not the values but rather some integer or string code from client side to the server side (it could be done with plain HTML), and then use an if statement on the server-side (PHP in your case). In this case, that is also possible to insert the numbers to the HTML form with PHP like that:
<input type='hidden' name="category" value=" <?php echo $some_code; ?> " />
You may store arrays in sessions so make somethings like $_SESSION['custom_pages'] where each key is the name of page (or id) and values - are arrays of 'socnetwork', 'cost',..
session_start();
$_SESSION['form1'] = ['socnetwork'> = '1',
'cost' => '15',
'soccount' => '100];
....
....
$_SESSION['form2'] = ['socnetwork'> = '2',
'cost' => '55',
'soccount' => '700];
A submit button adds its name to the $_POST button, so if you name your buttons you know which button the visitor used.
E.g
<form action="somepage.php">
<input type="submit" name="form1" value="Submit!">
</form>
<form action="somepage.php">
<input type="submit" name="form2" value="Submit other form!">
</form>
<?php var_dump($_POST); ?>
would give
array(1) { ["form1"]=> string(7) "Submit!" }
array(1) { ["form2"]=> string(18) "Submit other form!" }
And from that point it is a matter of checking whether a certain key exists.

associative array with web form

good day all ,, I am new learner and trying to make an associative array for jobs which user inputs the id, title and description but it is not correct ,,can u guide me through this ?
I also want to search for jobs by its title or description and return the job id ,
Thanks alot
<html>
<body>
This form is for storing array of jobs with ID and description for each
<form method = "post" >
input job iD <input id="jobid">
input jobname <input id="jobname">
Write a description <input id="jobdesc">
<input type="submit" value="click to store input" >
</form>
</body>
</html>
<?php
$jobs_array = array();
$jobs_array[] = array ($_POST['jobid'] ,$_POST['jobname'], $_POST['jobdesc']);
?>
You do not need to separate the values like
$_POST['jobid'] ,$_POST['jobname'], $_POST['jobdesc']
and enclose them in an array. Because, they are originally formed that way. When a user submits a post with multiple values, all those values are stored in the super global array $_POST so, instead of separating and then, attaching them inside an array, just depend on this one only, because it has all you need inside.
$all_arrays = $_POST;
Tweaked your markup a bit to
<html>
<body>
<p>This form is for storing array of jobs with ID and description for each </p>
<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "post" >
<p><label for = "jobid">input job iD</label> <input type = "text" name = "jobid" id="jobid"></p>
<p><label for = "jobname">input jobname</label><input type = "text" name = "jobname" id="jobname"></p>
<p><label for = "jobdesc">Write a description</label><input type = "text" name = "jobdesc" id="jobdesc">
<input type="submit" value="click to store input" >
</form>
</body>
</html>
<?php
$jobs_array = array ($_POST['jobid'] ,$_POST['jobname'], $_POST['jobdesc']);
?>
you can access jobid with $jobs_array[0] now, and so on.
An associative array is one where you have a value in an array which can be accessed by a key - that acts as the index.
In your code, as shown below, you are assigning a value to the array without a key thus it isn't associative. Furthermore, you are adding an array to the array making it multidimensional which is inappropriate in this situation.
$jobs_array[] = array ($_POST['jobid'] ,$_POST['jobname'], $_POST['jobdesc']);
The code should look like this:
$jobs_array = array("job_id" => $_POST['jobid'], "job_name" => $_POST['jobname'], "job_description" => $_POST['jobdesc']);
Also, the reason why the $_POST variables are not set is because you're using id rather than name. id refers to the stylesheet whereas name refers to how the data in the field can be accessed.
For the second part of your question, you need to be using a database to store the jobs, and from there, you can run queries whereby you are able to search through the rows by its id, and return an array of results.

Dynamic forms and PHP

Ive started working on a dynamic form script that allows a user to add form elements via Jquery, which is then in turn submitted to a PHP script.
I'm just after some feedback on ways to achieve this. At the moment I have the following:
When a user adds a form element the element is added with the following name array:
<textarea name="element[text][123]">
<input type="text" name="element[input][456]" />
As I need to know the type of form element that was submitted I am using a multidimensional array called 'element[][]' where the first level of the array is the type of element and the second element of the array is a unique ID and the value.
When I var_dump() This after submission PHP outputs:
array
text => array
123 => string 'The textarea value'
input => array
456 => string 'The input field value'
Im working on the PHP side of the script now and just wondering if there is a better way to do this.
Any thoughts?
UPDATE
I have to change the way that Im doing this as the array keynames are not unique.
If the user adds two textareas
<textarea name="element[text][123]">
<textarea name="element[text][456]">
When the user adds a form element, the element can be dragged so the positioning can be changed after the element was created. This allows a user to add an element but then move it to where they want it to appear.
PHP handles this ordering fine and accepts the array in the order that the form is submitted, however as mentioned above if the key names are the same then the order will be broken.
On the PHP side I need to know
the type of form field
the value of the form field
the unique ID, which is just a timestamp, of the form field
I think I might need to do what Cole mentioned, assigning the names as:
element[text_123]
I can then explode the keyname on '_' to determine the type and the identifier.
UPDATE
I took the script Jack posted and slightly modified it
$vars = $_POST['element'];
foreach ($vars as $id => $vals)
{
// $vars[id] outputs the ID number
// $vars[vals] is the array containing the type and value
echo "This fields ID is $id. ";
foreach($vals as $key => $value)
{
echo "Type was: $key and the value was: $value <br />";
}
}
A quick test of this outputted
This fields ID is 1338261825063. Type was: heading and the value was: xzczxczxczxczxczxc
This fields ID is 1338261822312. Type was: heading and the value was: asdasdasdasdad
From this I know the identifier and the array that it belongs to, the type and the value, but I also know the order that the data was submitted.
From that I can wrap my data in markup, perform any additional operations and then insert the data into the database.
Looks okay; you could also consider something like this (it introduces more fields though, so you must really think the benefit is worth it):
<input type="hidden" name="element[123][type]" value="text" />
<input type="hidden" name="element[456][type]" value="input" />
<textarea name="element[123][value]">
<input type="text" name="element[456][value]" />
Then you can do this:
foreach ($_POST['element'] as $name => $info) {
// $info['type'] is 'text' or 'input'
// $info['value'] is the user input
}

Is there some list of input's IDs or names of Form after the script was sent?

Let's imagine I got this:
index.php generates form with unpredictable number of inputs with certain IDs/Names and different values that can be edited by user and saved by script.php
<form action="script.php" method="post">
<input id="1" name="1" type="text" value="1"/>
<input id="24" name="24" type="text" value="2233"/>
<input id="55" name="55" type="text" value="231321"/>
</form>
Script.php:
Here I need to get something like array of all inputs that were generated by index.php and save every value that corresponds to its id/name.
Is there a way to do this?
i may be missing something in your question, but the $_POST variable will contain all the name => value pairs you're asking for. for example, in your above HTML snippet:
print_r($_POST);
// contains:
array
(
[1] => 1
[24] => 2233
[55] => 231321
)
// example access:
foreach($_POST as $name => $value) {
print "Name: {$name} Value: {$value} <br />";
}
Use an array_keys on the $_POST variable in script.php to pull out the names you created and use those to get the values.
$keys = array_keys( $_POST );
foreach( $keys as $key ) {
echo "Name=" . $key . " Value=" . $_POST[$key];
}
It sounds like you're using a class or framework to generate your forms, you need to read the documentation for the framework to see if/where it's collecting this data.

Categories