get id of checkbox created from loop php - php

How would i get the value of the checkboxes that have been selected from these checkboxes created with a loop in php:
<?php
while($rowequipment = mysql_fetch_assoc($sqlequipment)) {
echo '<input type="checkbox" name="equipment[]" value="'.$rowequipment['equipmentid'].'"/>
<input type="text" name="count[]" id="count[]" size="3" value=""/>' .
$rowequipment['description']."<br />";
}
?>

The above commenters are wrong: The name attributes for HTML form elements are of type CDATA. Thus, your code is correct. HTML definition found here.
The id attributes are useless, unless you need to operate using JavaScript over the DOM tree. In case you just want to process the control's values using PHP, just drop the ids.
In case you POSTed data, this iterates over all elements named equipment[]:
foreach( $_POST[ 'equipment' ] as checkBoxIndex => checkBoxValue ) {
echo '<br />Checkbox ' . checkBoxIndex . ' has value [' . checkBoxValue . ']';
}

Assuming you're generating these checkboxes in your PHP code and want to match those with checked = "checked" attribute later (maybe in other file).
As others mentioned, the HTML made by the code is not valid, fix it and then you can get what you want using DOM and XPath:
$html = new DOMDocument();
$html->loadHTML($yourMarkup);
$xpath = new DOMXpath($html);
$checkboxes = $xpath->query("*/input[#type='checkbox' and #checked='checked']");
if (!is_null($checkboxes)) {
foreach ($checkboxes as $checkbox) {
echo $checkbox->nodeValue;
}
}
If you want to get the checkboxes values on form post, then use $_POST['key'] which key is checkbox name attribute.

Related

Getting an alternate value for an unchecked checkbox?

I've seen a solution here that I, quite frankly, don't understand.
On the administration side of a website I'm working on, an administrator can edit blog posts. When the administrator goes to the page to edit the blog post, it also displays all of the comments on that post. Instead of adding a new table for each new blog post which contains comments, I simply created one table which holds all the information for the blog post, including a column for the comments.
Comments and comment-content is delimited. I.E. internally, a blog post comment column would look similar to this...
Name:Content:Email>Name2:Content2:Email
Etc.
This is how I display the comments on the admin page:
$post_query = "SELECT * FROM `$blog_table` WHERE id=$identifier";
$post_result = $connection->query($post_query);
$post = $post_result->fetch_assoc();
$comments_value = $post["comments"];
$original_comments_array = explode(">", $comments_value);
$comments_array = [];
foreach($original_comments_array as $comment) {
$individual_comment_array = explode(":", $comment);
$comments_array[] = $individual_comment_array;
}
foreach($comments_array as $index=>$comment) {
if ($comment_deletions_array[$index] === $index) {
$checked = "checked";
}
echo '<div class="content-border comment-margin"><span class="comment-name">';
echo $comment[0];
echo '</span><br /><p class="comment-content">';
echo $comment[1];
echo '<br /></p>';
echo $comment[2];
echo '<br /><br /><input name="comment_deletions[]" type="checkbox" value="' . $index . '" ' . $checked . '/> Delete This Comment';
echo '</div>';
}
As you may have noticed from the code above, each comment renders with its own checkbox input, the value of which is determined by the index.
Each checkbox shares the same name. I get all the values of the checkboxes like this:
$comment_deletions_array = $_POST["comment_deletions"];
In the snippet I provided earlier, there is an if statement within the foreach loop which determines if the comment was marked for deletion, and if so checks the check box. (This function is to replace the user's input if there was an error.)
The problem is that the indexes do not line up. If there is a checkbox which is not checked, it does not return false or null or anything of the sort to the $comment_deletions_array rather the array is just populated by value of the next input which WAS checked.
Is there a way I can return a value if the checkbox is not checked in order to maintain the correct index?

Grabbing hidden inputs as a string (Using PHP Simple HTML DOM Parser)

So I have a form that has 4 inputs, 2 text, 2 hidden. I've grabbed the two text input values from the name, which are (get_me_two, get_me_three) and I've also grabbed the form action which is (get_me.php). What I'm looking to do now is grab the 2 hidden inputs, but not the values. I want to grab the inputs themselves.
E.G: Here's my form:
<form action="get_me.php" method="post">
<input type="text" name="get_me_two">
<input type="text" name="get_me_three">
<input type="hidden" name="meta_required" value="from">
<input type="hidden" name="meta_forward_vars" value="0">
</form>
And what I want to grab from here is the two hidden inputs, Not the values, the complete string.
I'm not sure how to grab these using: PHP Simple HTML DOM Parser, if anybody knows a way that would be great, if not, if there's an alternative that also would be great. Once I've grabbed these I plan on passing the 2 input values to another page with the hidden strings, and of course the form action.
Also, if anybody is interested here's my full code, which includes the simple html dom functionality.
<?php
include("simple_html_dom.php");
// Create DOM from URL or file
$html = file_get_html('form_show.php');
$html->load('
<form action="get_me.php" method="post">
<input type="text" name="get_me_two">
<input type="text" name="get_me_three">
<input type="hidden" name="meta_required" value="from">
<input type="hidden" name="meta_forward_vars" value="0">
</form>');
// Get the form action
foreach($html->find('form') as $element)
echo $element->action . '<br>';
// Get the input name
foreach($html->find('input') as $element)
echo $element->name . '<br>';
?>
So, the end result would grab the 3 values, and then the 2 hidden inputs (full strings). Help would be much appreciated as It's driving me a little mad trying to get this done.
I don't use the SimpleDom (I always go whole-hog and use DOMDocument), but couldn't you do something like ->find('input[#type=hidden]')?
If the SimpleDOM doesn't allow that sort of selector, you could simply loop over the ->find('input') results and pick out the hidden ones by comparing the attributes yourself.
If you use DomDocument, you could do the following:
<?php
$hidden_inputs = array();
$dom = new DOMDocument('1.0');
#$dom->loadHTMLFile('form_show.php');
// 1. get all inputs
$nodes = $dom->getElementsByTagName('input');
// 2. loop through elements
foreach($nodes as $node) {
if($node->hasAttributes()) {
foreach($node->attributes as $attribute) {
if($attribute->nodeName == 'type' && $attribute->nodeValue == 'hidden') {
$hidden_inputs[] = $node;
}
}
}
} unset($node);
// 3. loop through hidden inputs and print HTML
foreach($hidden_inputs as $node) {
echo "<pre>" . htmlspecialchars($dom->saveHTML($node)) . "</pre>";
} unset($node);
?>

What is wrong with this foreach loop?

I am trying to allow my users to update quantities in the database, by providing them some input fields, I know that the sql update query is perfect, because if i DONT use the foreach loop, it will submit and update the last textfield only.
But I need the foreach loop so it will loop through all the textfields and update them all in the database. Can somebody please help me figure out why it's not updating with this foreach loop? Lots of thanks in advance :)
foreach($_POST['items'] as $p=>$q)
{
// working sql code is in here.
}
And the fields are dynamically generated like so:
$ct->data[$key][0]='<input type="text" value="'.$ct->data[$key][0].'" name="product" />';
$ct->data[$key][1]='<input type="text" value='.$ct->data[$key][1].' id="qty" name="items[' . $ct->data[$key][1] . ']" />';
$ct->data[$key][2]='<input type="submit" value="Update Item">';
$ct->data[$key][3]='<p name="price">'.$ct->data[$key][3].'</p>';
You should ALWAYS check if a variable exists. That's no more that normal and should have been lession 1.
You can't iterate over $_POST['items'] if $_POST['items'] doesn't exist (obviously). So you have to check if the form has been submitted.
One way is:
if ( isset($_POST['items']) ) {
// foreach ( $_POST['items'] ....
}
I always like to be on the safe side and check for type as well:
if ( isset($_POST['items']) ) {
// form submitted at least
if ( is_array($_POST['items']) ) {
// and it's an array as it should be
foreach ( ....
}
}
POST variables are never set in a GET request, so doing the foreach first time on a page is useless. That's what the check is for: 'is the form submitted and do the necessary post vars exist?'
What values are you seeing?
foreach($_POST['items'] as $p=>$q) {
print "$p: $q\n";
}
The name of the items input field should just be items[].
So:
# Good
$ct->data[$key][1]='<input type="text" value='.$ct->data[$key][1].' id="qty" name="items[]" />';
# Bad
$ct->data[$key][1]='<input type="text" value='.$ct->data[$key][1].' id="qty" name="items[' . $ct->data[$key][1] . ']" />';

How to retrieve the Selected checkbox names ( Multiple Selected) in PHP?

I had multiple checkbox which is generated using loop. After submitting the form I want to get the names of the selected individual checkbox to store it in database as id. Please help me.. Thanks in advance
Code i used for generating checkbox in loop:
while($arrayRow = mysql_fetch_assoc($rsrcResult))
{
$strA = $arrayRow["area_id"];
$strB = $arrayRow["area_name"];
echo "<div class=\"area_check\"><input type=\"checkbox\" id=\"covarea[] \" />$strB</input></div>";
}
This code I used for getting names for it didnt worked. It only returned state of check box as ON
while (list ($key,$val) = #each ($box))
{
$aid=$val;
echo $aid;
}
If the set of checkboxes is marked up as so
<input type="checkbox" name="food[]" value="Cheese">
<input type="checkbox" name="food[]" value="Ham">
Then any checked values are accessed as an array from $_POST['food']
Obviously with a code example, as #rajasekar points out, it would be easier to recommend an approach
The id for each element is optional, but should/must be unique.
Form elements must have a name attribute, or they will not be submitted (use "covarea[]" for the name for all the chexboxes.
Checkboxes must have a value attribute, or they will be submitted with value "on".
You must ensure that $strA and $strB do not have HTML meta characters or your generated HTML will be invalid.
Your example had a space after the "[]" in the id, btw.
Perhaps like this.
$n = 0;
while($arrayRow = mysql_fetch_assoc($rsrcResult))
{
$strA = $arrayRow["area_id"];
$strB = $arrayRow["area_name"];
$n++;
echo "<div class=\"area_check\"><input type=\"checkbox\" id=\"covarea${n}\" name=\"covarea[]\" value=\"${strA}\"/>$strB</input></div>";
}

Finding name attributes inside a tag using php

i want to find the name attribute with in a tag in a form using php4 . Does any one help me how it find..
eg
<input type="text" name="txt_name" value="" >
I want to know name of all the fields
You need a library/code which implements an HTML DOM, look at these SO questions for more information.
When you submit a form, a url is send to the server in the form "name=value&name1=value1" etc. Here the "name" stands for the attribute "name" of an html element. So If you are using the $_GET or a $_POST then you can get the form item names in an array as follows
$names=array();
foreach($_GET as $key => $value)
{
$names[] = $key;
}
print_r($names);
You can use simple html dom as mentioned by Ignacio Vazquez-Abrams
Add it in your code like this
require_once('Simple_html_dom.php');
To use it I initialized it using this line
$html = new Simple_html_dom();
Load a page or link using the line
$html->load_file('http://www.yourste.com/yourpage.php');
to parse and find this element
$e = $html->find("input", 0);
the echo the value of attribute name
echo $value = $e->name

Categories