edit value in session - php

Scenario :
I have an simple php form to calculate things and calculate prices.
Now im stuck at my edit function.
I have a simple switch switch ($_GET['actie']) with cases like add , edit and delete.
This is my session : $_SESSION['data'][] = $_POST;
Edit Case :
if (isset($_POST['submitnieuw']))
$data['lengtezijde'][$_GET['key']] = $_POST['nieuw'];
Laden(0);
Edit Form:
else
echo $_GET['key'];
<form action="index.php?actie=wijzigen" method="post">
<input type="text" name="nieuw">
<input type="submit" name="submitnieuw" value="submit">
<input type="hidden" name="ky" value="$_GET['key;]">
</form>
break;>
i can see the key of the value i want to edit but it wont edit the $data['lengtezijde'] value
if some things are missing or my question is unclear let me know.

In your edit case you are using the GET value of the key, but from your form it looks like you should be using a POST value here instead. Try changing this:
$data['lengtezijde'][$_GET['key']] = $_POST['nieuw'];
To this:
$data['lengtezijde'][$_POST['ky']] = $_POST['nieuw'];

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; ?>

Keep Request when requesting same route with POST and GET?

I'm trying to make a simple form that is validated and errors should be shown. Also, the values of the fields should stay.
I'm using simple routing code to determine which page to show.
My problem is that the values of the form always reset when I submit it.
I googled a bit and found that when the Request changes, the form values get lost.
That's a small example that shows what I want to achieve:
$route = $_SERVER['REQUEST_URI'];
switch ($route) {
case '/kontakt':
?>
<form method="POST" action="/kontakt">
<input type="text" required name="test">
<input type="submit">
</form><?php
break;
}
After submitting the entered value should stay in the field.
So how can I keep the Request when routing to the same route but one time with POST and one time with GET without changing the form value to use the _POST array?
Lets first grab which request we need to use to get the request arguments.
$request =& $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;
It would probably be a good idea here to check it is set, if it isn't - just leave it blank.
$name = $request['name'] ?? ''; # PHP 7+
$name = isset($request['name']) ? $request['name'] : ''; # PHP 5.6 >
You can then do your routing
# switch: endswitch; for readability
switch(($route = $_SERVER['REQUEST_URI'])):
case '/kontack': ?>
<form method="POST" action="/kontakt">
<input type='text' value='<?= $name; ?>' name='name' />
....
<?php break;
endswitch;
This will then continuously insert the name back in to the value field. However, if you visit a new page and then come back - it will be gone. If you want it to stay at all times, through-out any route, you can use sessions.
session_start();
# We want to use the request name before we use the session in-case the user
# Used a different name to what we previously knew
$name = $request['name'] ?? $_SESSION['name'] ?? ''; # PHP 7
$name = isset($request['name']) ? $request['name'] : isset($_SESSION['name']) ? $_SESSION['name'] : ''; # PHP 5.6 >
# Update what we know
$_SESSION['name'] = $name;
Note: I showed both PHP 5.6> and PHP 7 examples. You only need to use one based on which PHP version you're using.
When you are getting to the route in the first time, then send a HTML-valueAttribute-variable as null. When you go back to the route after posting send the post value to the HTML-valueAttribute-variable:
When you reach the route the first time:
<?php
//Value that is sent to the view/page when accessing route without having posted a value
$testValue=null
?>
<form method="POST" action="/kontakt">
<input type="text" required name="test"
<?php
if($testValue != null)
{
echo "value='".$testValue."'";
}
?>
>
<input type="submit">
</form>
When you use the route after have posted:
<?php
//Value that was posted is sent to view/page
$testValue=$POST['test']
?>
<form method="POST" action="/kontakt">
<input type="text" required name="test"
<?php
if($testValue != null)
{
echo "value='".$testValue."'";
}
?>
>
<input type="submit">
</form>

How can I add text to the end of user input?

I have been given some spaghetti code for a login page to fix.
We've got two input fields ID and Password.
Here's what I've been asked.
So in terms of a user inputting their ID, I want to add '#email.com' onto the end.
Im assume placeholder="#email.com" would work if i could align it to the right, but I also need to it to be added into the POST method. So if the user entered 'ID123' it would post 'ID123#email.com'
Here is the form:
<form action="command.php" formmethod="post">
<div class="ID">User ID:<br><input name="ID" type="text"><br></div>
<div class="Pass"> Password:<br><input name="pwd" type="password"></div>
<input id="submit" type="submit" value="Sign In">
Can anyone help? Is it even possible?
Placeholder in the input type in HTML will just give a hint in a textbox and it will not be added into the input of the user. What you need to do is catch the input type in the command.php you created and add it.
for example, in the command.php
$ID = $_POST['ID'].'#gmail.com'
When you submit the form, your POST data will contain:
$_POST['ID'] = 'test_id'; // Sample Data
$_POST['pwd'] = 'test_pwd'; // Sample Data
So, if you want to add #email.com at the end of the ID, you could simply concatenate the field:
$_POST['ID'] .= '#email.com';
Note: This is a simple solution and doesn't specify SQL injection/vulnerability prevention.
I think you want something like if anyone give ID123#email.com as input it will not change but if only give ID123 then it will be ID123#email.com,then :-
$userId=$_POST['ID'];
if(!filter_var($userId, FILTER_VALIDATE_EMAIL)) {
$userId=$userId.'#email.com';
}
echo $userId;

PHP avoiding a long POST

This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}

$_POST variable name is variable, how to retrieve?

Users of my website can generate a custom form. All the fields are saved in a database with a unique ID. When someone visits the form, the fields 'name' attribute is field*ID*, for example
<p>Your favorite band? <input type="text" name="field28"></p>
<p>Your Favorite color? <input type="text" name="field30"></p>
After submitting the form, I use php to validate the form, but I don't know retrieve the value of $_POST[field28] (or whatever number the field has).
<?
while($field = $query_formfields->fetch(PDO::FETCH_ASSOC))
{
$id = $field[id];
//this doesn't work!!
$user_input = $_POST[field$id];
//validation comes here
}
?>
If anybody can help me out, it's really appreciated!
Add some quotes:
$user_input = $_POST["field$id"];
I'd suggest taking advantage of PHP's array syntax for forms:
<input type="text' name="field[28]" />
You can access this in php with $_GET['field'][28]
$user_input = $_POST['field'.$id];
Remember that you are using a string for the first part of the input name, so try something like: $user_input=$_POST['field'.$id];.
Also, I would suggest calling them into an array to retrieve all data:
<?php
$user_inputs=array();
while($field=$query_formfields->fetch(PDO::FETCH_ASSOC)) {
$id=$field['id'];
$user_inputs[]=$_POST['field'.$id];
}
?>

Categories