making radio fields sticky [duplicate] - php

This question already has answers here:
Can I use white spaces in the name attribute of an HTML element? [duplicate]
(2 answers)
Closed 7 years ago.
Hi I am trying to make a form sticky. It creates a grid, and the user can then select a value for each row.
$subjectListArray has values of subject names like 'english', 'maths','speaking and listening' and $gradeSetArray carries a selection of grades like a,b,c etc
When I press submit I want the values that were selected to stay selected.
It works fine for subjects with NO SPACES in their names. As soon as I introduce an array value like 'Speaking and listening' its not sticky.
SO the space is causing me a problem.
<form>
<?php
foreach ($subjectListArray as $subject){
echo "<tr><td>$subject</td>";
foreach ($gradeSetArray as $grade){
echo '<td><input type="radio" name="'.$subject.'" value="'.$grade.'" ';
if ( isset($_POST[$subject])and $_POST[$subject]==$grade){
echo 'checked="checked"';
}
echo ' /></td>';
}
echo "</tr>";
}
?>
<input type="submit" name="submitPupilData" value="Input data" />
</form>
Here's a little of the html produced:
<td>
<input type="radio" value="p2iic" name="Speaking and Listening">
</td>
So for some reason my if ( isset($_POST[$subject])and $_POST[$subject]==$grade) isn't working if there's a space
What can I do in order to keep the spaces in the names and keep the from sticky?
Thanks
As per Jakar I printed out the $_POST and I noticed that the spaces were being replaced by _ characters thus Array ( [Health_and_well_being] => p2iic

It's not possible to use spaces in HTML name attributes. For more information checkout Can I use white spaces in the name attribute of an HTML element?

Related

Php Post method not passing string after space character [duplicate]

This question already has answers here:
HTML PHP form entry problem with space?
(2 answers)
Closed 5 months ago.
I am having trouble with the POST method after submitting a form. It is not passing the complete string after submitting the form, but it shows correctly in the "select" & "option" html.
in the database i have a table called "administradores" with a column called "id" and other called "administrador":
id: 1
administrador: "Alejandro Salgado"
this is the php code:
function listAdministradores(){
global $conn;
$result = $conn->query("SELECT * FROM administradores");
while($row = $result->fetch_assoc()){
echo '<option value='.$row["administrador"].'>'.$row["administrador"].'</option>';
}
}
this is the html code:
<form action="./includes/crearpropuesta.inc.php" method="post">
<label for="administrador" class="form-label pt-3">Administrador:</label>
<select name="administrador" id="administrador" class="form-select">
<?php listAdministradores() ?>
</select>
And it shows the name "Alejandro Salgado" correctly:
html result
but when I submit the form and var_dump($_POST["administrador"]), it returns only the first name "Alejandro":
string(9) "Alejandro"
What is going on?
To include characters separated by spaces, you need to enclose the data with quotation marks (in your case double-quotation)
Hence, please change
echo '<option value='.$row["administrador"].'>'.$row["administrador"].'</option>';
to
echo '<option value="'.$row["administrador"].'">'.$row["administrador"].'</option>';

How to pass multiple checkbox values to php [duplicate]

This question already has answers here:
Get $_POST from multiple checkboxes
(5 answers)
Getting checkbox values on submit
(10 answers)
Closed 3 years ago.
Currently i have a HTML form that collects some metadata about some files, and each user as to fill some fields. I want to register some keywords about the data. I could ask them to write the keywords by hand on a normal text box, but i would prefer to have a list of checkboxes of about 10/15 values.
Then i need to pass only the checked values to a PHP file, using $_POST. My problem is that i assign a variable to those values, and then i call that variable in a DOM event. I´m generating a XML file, and currently i have the HTML ready to register these keywords in text input. I understand how to create the checkboxes, and pass them as an array to PHP., by reading other questions here. But i can´t understand how to pass this array to a $dom->createElement situation, and preferably separated by commas.
PHP
//Pull data from HTML form
$keywordsString = $_POST['keywords'];
// Creates xml document
$dom = new DOMDocument();
$dom->encoding = 'utf-8';
$dom->xmlVersion = '1.0';
$dom->formatOutput = true;
$xmlFileName = 'example_example.xml';
// Adds metadata to xml
$metadata = $dom->createElement('MD_Metadata');
$idInfo = $dom->createElement('identificationInfo');
$descriptiveKeywords = $dom->createElement('descriptiveKeywords');
$CharacterString = $dom->createElement('CharacterString', $keywordsString);
$descriptiveKeywords->appendChild($CharacterString);
$idInfo->appendChild($descriptiveKeywords);
$metadata->appendChild($idInfo);
$dom->appendChild($metadata);
$dom->save($xmlFileName);
I can´t figure out how to pass checkbox values to that $keywordsString , but separated by commas. The rest i can understand and write, using the other questions about this kind of issue.
Thanks in advance for all help provided.
Your html should look like this:
<form action="" method="post">
<input name="choice[]" type="checkbox" value="1" />
<input name="choice[]" type="checkbox" value="2" />
<input name="choice[]" type="checkbox" value="3" />
<input name="choice[]" type="checkbox" value="4" />
<input type="submit" value="order" />
</form>
In PHP, you can iterate over using foreach loop. Place the below code at the top of your html form:
A small note from basics, when posting data via post method, you need to apply Post redirect get design pattern to prevent form re-submissions.
If the data you are sending is not sensitive, you can do it via get request.
<?php
if($_POST):
foreach($_POST['choice'] as $val)
{
echo $val . "<br>";
}
endif;
?>

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

Disable multiple checkboxes with javascript

I've got a problem with my JS function. I'll explain that to you with my code and a Prt Sc.
Code = http://jsfiddle.net/dKeRf/
This is a Php function and JS function.
Screen = http://img824.imageshack.us/i/antoe.png/
If one of the 2 checkbox over the table is checked, all the checkbox in the two table must be disabled. For the moment It works for the first checkbox, but not for the second, and I ask you why ? :)
I use '10' in my 'For' jut for a test, I'll change that latter by the number of row of the table.
Thanks for your help and have a good day !
Add a class to all of the checkboxes:
<input class="the_checkbox" id='{unique_id}' name='module[]' type='checkbox' value='{unqiue_value}'>
<input class="the_checkbox" id='{unique_id}' name='module[]' type='checkbox' value='{unqiue_value}'>
<input class="the_checkbox" id='{unique_id}' name='module[]' type='checkbox' value='{unqiue_value}'>
<input class="the_checkbox" id='{unique_id}' name='module[]' type='checkbox' value='{unqiue_value}'>
Then use jquery to update all of the checkboxes at once:
<script>
$(document).ready(function(){
$(".selectAll").click(function() {
if($(".selectAll").attr("checked")) {
$(".the_checkbox:checkbox").attr("disabled", true);
} else {
$(".the_checkbox:checkbox").removeAttr("disabled");
}
});
});
</script>
UPDATE: Changes the answer to use the .class name for updating the checkboxes instead of the ID so that the ID can remain unique and conform to HTML standards.
IDs are not allowed to start with a number, they must start with a letter. So document.getElementById(1234) will fail (I think IE might not say anything and allow it, but FF doesn't work). You should be ok with just putting a letter in front of the number and change the getElementById to document.getElementById('cb'+id2);.
Also, just a side note, if you are passing in this to a function onClick, that parameter is a reference to the element that was clicked. So there is no need to get box.id and then do document.getElementById(checkId). technically document.getElementById(checkId) is === box so you could just say box.checked.
http://www.w3.org/TR/html4/types.html#h-6.2. This is the spec that talks about ID attribute naming requirements:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
Edit:
Even better than using document.getElementById() to select each checkbox, would be to use document.getElementById() on a parent element that the checkboxes you want to disable share (such as the table they are in) and then use document.getElementsByTagName('input') to get a collection of all the checkboxes and loop/disable them with that. So the JS disable code would look like:
Some table:
<input type='checkbox' onClick='checkCBs(this,"someTable1");'>
<table id='someTable1'>
<tr>
<td>This is checkbox 1:</td>
<td><input type='checkbox' name='group1' value='checkbox1'></td>
</tr>
<tr>
<td>This is checkbox 2:</td>
<td><input type='checkbox' name='group1' value='checkbox2'></td>
</tr>
</table>
The code:
function checkCBs(box, parent){
var parent = document.getElementById(parent),
CBs = parent.getElementsByTagName('input'),
i;
//loop through all input elements
for(i=0;i<CBs.length;i++){
//make sure the input is a checkbox
if(CBs[i].type && CBs[i].type=='checkbox'){
//set disabled on this checkbox to opposite
//of whether box is checked.
CBs[i].disabled = !box.checked;
}
}
}

Categories