no values in my string from an imploded post array? PHP - php

Started learning PHP today so forgive me for being a noob. I have a simple HTML form where the user inputs 4 strings and then submits.
HTML form
<html>
<head>
<title>EMS</title>
</head>
<body>
<h1>EMS - Add New Employees</h1>
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
<table>
<tr><td>Enter a NAME:</td><td> <input type="text" name="name"></td></tr>
<tr><td>Enter a PPSN:</td><td> <input type="text" name="ppsn"></td></tr>
<tr><td>Enter a PIN :</td><td> <input type="text" name="pin"></td></tr>
<tr><td>Enter a DOB:</td><td> <input type="text" name="dob"></td></tr>
<tr><td></td><td><input type="submit" value="Add New Employee" name="data_submitted"></td></tr>
</table>
</form>
</html>
I want to implode the 4 elements in the $_POST["data submitted"] array to a string.
PHP
<?php
if (isset($_POST['data_submitted'])){
$employee = implode(",",$_POST['data_submitted']);
echo "employee = ".$employee;
}
?>
Why is it that when I run the project, Input the 4 strings into the form and submit that there is nothing contained within the employee string when its outputed? There is however a value in the employee string when I just implode the $_POST array like so without 'data_submitted'.
$employee = implode(",",$_POST);
The output of the $employee string is now - employee = will,03044,0303,27/5/6,Add New Employee
It contains the name,pps,pin,dob and this ADD New Employee value?
How do I just get the $employee string to contain just the name,pps,pin and dob from the $POST_[data_submitted] array?

If you wish to implode the submitted data, then you need to refer to the specific items, as follows:
<?php
$clean = [];
if (isset($_POST['data_submitted'])){
// one way to deal with possibly tainted data
$clean['name'] = htmlentities($_POST['name']);
$clean['ppsn'] = htmlentities($_POST['ppsn']);
$clean['pin'] = htmlentities($_POST['pin']);
$clean['dob'] = htmlentites($_POST['dob']);
$employee = implode(",",$clean);
echo "employee = $employee";
}
Never use submitted data without first checking to make sure that it is safe to do so. You need to validate it. Since the OP doesn't specify what kind of data the named inputs "ppsn", "pin", "dob" pertain to, this example does a minimum of validation. Each input might require more or something different.
Whether you're new or familiar with PHP, it is a good idea to frequently read the online Manual.

First, you need to know that php will treat value in the format: value="value here" as string.
So, calling implode(",",$_POST['data_submitted']); will return Add New Employee as declared here: <input type="submit" value="Add New Employee" name="data_submitted">.
From your question:
How do I just get the $employee string to contain just the name, pps, pin and dob from the $_POST[data_submitted] array?
Solution
1. Unset the <code>$_POST['data_submitted']</code> index in the $_POST super global variable
2. Implode it
// Unset the $_POST['data_submitted'] index
$post_data = unset( $_POST['data_submitted'] );
// Format the post data now
$format_post_data = implode( ",", $post_data );
// Escape and display the formatted data
echo htmlentities( $format_post_data, ENT_QUOTES );

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

Date entry for first_name, lastname, and job title should be in camel case format even if the user enters all capitalized letters

So this is my code for the first_name. I have no clue why it does not work whenever I add an entry.
First Name: <input type="text" name="first_name" value="<?php function convertString($first_name){
$first_name=htmlentities(strip_tags($first_name));
$lowercaseFName = strtolower($first_name);
$ucFName = ucwords($lowercaseFName);
return $ucFName;} ?>"/> // I changed it with echo but nothing changed.
My code doesn't change the format of the text.I tried inputting in all caps and it will show as is. Am I missing something or doing it wrong?
The inputted text if all in capital must still be shown as Camel Case format in the table, like this:
First Name: MARIA YLONA (in the form)
First Name: Maria Ylona (in the table) - this is another .php file for viewing of the data entries
Seeing you didn't post your html form or how it's used, am submitting the following as a successful piece of code and using !empty() against a POST array with form tags and an isset() for the submit input.
Btw, functions and variables assignments should be used seperately than in inputs/form elements.
Create a function, then pass it inside the input with the parameter.
<?php
function convertString($first_name){
$first_name=htmlentities(strip_tags($first_name));
$lowercaseFName = strtolower($first_name);
$ucFName = ucwords($lowercaseFName);
return $ucFName;
}
if(isset($_POST['submit'])){
if(!empty($_POST['first_name'])){
$first_name = $_POST['first_name'];
}
}
// here initialize $first_name to something meaningful
?>
<form method="post">
First Name: <input type="text" name="first_name" value="<?php echo(convertString($first_name)) ?>"/>
<input type="submit" name="submit" value="Submit">
</form>
Footnotes:
In regards to what Marc mentioned about McDonald's -> mcdonald's -> Mcdonald's and my MacDonald in comments...
Consult the following here on Stack which may prove to be useful:
Given upper case names transform to Proper Case, handling "O'Hara", "McDonald" "van der Sloot" etc
Data Cleanup, post conversion from ALLCAPS to Title Case
You mention the use of a database, but haven't posted relative code and would be beyond the scope of the question.
To clarify what aynber meant in the comments:
<?php
function convertString($first_name){
$first_name=htmlentities(strip_tags($first_name));
$lowercaseFName = strtolower($first_name);
$ucFName = ucwords($lowercaseFName);
return $ucFName;
}
// here initialize $first_name to something meaningful
?>
First Name: <input type="text" name="first_name" value="<?php echo(convertString($first_name)) ?>"/>

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.

How to pass multiple values to insert statement from dynamic number of html textboxs?

I am doing a project in which as per number getting by GET method, I display dynamic number of HTML Textbox for storing Multiple values. I am giving each textbox unique name+id in ascending manner starting from 1(Like textbox1,textbox2). Now I want that when I click on submit button, it should fire an insert statement which insert all textbox values at once. I know I can do by array, but my question is that how to get all textbox's value in an array and How to perform insert statement?
I have done following code:
Here is PHP Code for submit button:
$schedules = array();
if(isset($_POST['submit']))
{
for($d=1; $d<=$_GET['totalDay'] ;$d++)
{
array_push($schedules,$_POST['txtSchedule'.'$d']);
}
print_r($schedules);
}
Here is the html code:
<form method="post">
<table>
<tr>
<td>Day</td>
<td>Schedule</td>
</tr>
<?php
if(isset($_GET['tour_code']) and ($_GET['totalDay']!=1))
{
$tour_code = $_GET['tour_code'];
$total = $_GET['totalDay'];
$i=0;
do
{
$i=$i+1;
?>
<tr>
<td><?php echo $i;?></td>
<td>
<input name="txtSchedule<?php echo $i;?>" type="text" size="30"/>
</td>
</tr>
<?php
$start = date('Y-m-j',strtotime($start.'+1 days'));
}while($i!=$total);
}
?>
</table>
<input type="submit" name="submit" value="Add Tour Details" />
But I am getting an empty array.
Note: $total is coming through URLString's $GET method.
Below is the output of HTML:
Simplest thing first. You have an error, you can't use
array_push($schedules,$_POST['txtSchedule'.'$d']);
You must use DOUBLE QUOTES on the $d (single quotes won't evaluate d, it will literally read "txtSchedule$d" with a dollar sign, and not actually 0, 1,..., n)
array_push($schedules,$_POST['txtSchedule'."$d"]);
//or no quotes at all
array_push($schedules,$_POST['txtSchedule'.$d]);
(that may sovlve your problems)
But now let's get to how to make an array available to the $_POST object in the processing page via form naming conventions
You're not using array syntax, but you are oh-so close. In PHP, whatever is submitted needs to be of an expected format, and iterating txtSchedule0, txtSchedule1, ...txtScheduleN is not an Array(), but $_POST[] is an array that contains each (given what you've named your input fields, which is missing 1 small thing - square brackets).
What you need to do is be naming your inputs as an array is the array name followed by square brackets (arrayName[]), here is how you create an input array of the name txtSchedule (that way when you print_r($_POST['txtSchedule']) you get an Array())
<input name="txtSchedule[<?php echo $i;?>]" type="text" size="30"/>
I had the same issue when I started in PHP, you were forgetting the square brackets around [<?php echo $i;?>]
Just make sure that if you want to do an iteration over an array of inputs:
for($i=0; $i < count($_POST['txtSchedule']); $i++){
echo "They entered " . $_POST['txtSchedule'][$i] . " in the $i" . "th position";
}
... you have used the <input name="arrayName[$i]"> sytax, or even more simply <input name="arrayName[]"> for it to auto-magically generate an array on submit in the order the inputs were in the HTML page. The naming convention is so important, and since you have it wrong (you used arrayName0, arrayName1, ... arrayNameN instead of arrayName[0], arrayName[1], ... arrayName[n]), it will never be available to you as an array.
if i understand your question correctly you are trying to retrive user input from each textbox and save it in an array?
if so I would use jquery to select all textboxes and loop through them and retrive the value
If you are looking purely at the SQL syntax, then you can just append extra records to insert at the end of your query by providing more value sets:
INSERT INTO myTable (fieldName1, fieldName2) values ("Value1A", "Value1B"), ("Value2A", "Value2B")
If you looking at the PHP logic, then my first suggestion is to use the http POST method instead of GET. Then start with processing the $_POST fields:
$data= array();
foreach($_POST as $key => $value) {
if (preg_match('/^TextBox\d+$/', $key)) {
$data[] = $mysqli->real_escape_string($value);
}
}
The construct the SQL query based on the available data
if (count($data) > 0) {
$sql = 'INSERT INTO `myTable` VALUES("' . implode('"),("', $data).'")';
// log query
// execute query
// process query results
// redirect user to a thankyou page
header('Location: thankyou.php');
}
Note that the code assumes that you have a mysqli connection instance available at $mysqli
Not sure if this is what you are looking for but should give you at least a start..
String []ar=request.getParameterValues("name");
String cmd=request.getParameter("cmd");
if(cmd==null) cmd="";
if(cmd.equals("Submit")){
for(int i=0;i<ar.length;i++) {
insert logic;
<form method="post" action="page3.jsp">
<br/><input type="text" name="name"/>
<br/><input type="text" name="name"/>
<br/><input type="text" name="name"/>
<br/> <input type="submit" value="Submit" name="cmd"/>
</form>
Orignal post http://www.daniweb.com/web-development/jsp/threads/197777/insert-dynamic-textbox-value-in-database

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);
}
}

Categories