That title probably doesn't mean much but what I have is a form that is generated dynamically. I hooks into a table of products, pulls out there name. I then create a form that displays the product with a checkbox and textbox next to it.
<form id="twitter-feed" name="twitter-feed" action="<?php echo $this->getUrl('tweet/') ?>index/tweet" method="post">
<table><tr>
<?php
$model = Mage::getModel("optimise_twitterfeed/twitterfeed");
$products = $model->getProducts();
foreach ($products as $product){
echo '<tr>';
echo '<td>';
echo '<label for="'. $product .'">' . $product . '</label>';
echo '<br /><input type="text" class="hashtag" name="tags" id="tags" value="#enter, #product, #hastag"';
echo '</td>';
echo '<td><input type="checkbox" name="chk" id="'. $product .'"></td>';
echo '</tr>';
}
?>
<tr><td colspan="2"><input type="submit" name="submit" value="tweet"></td></tr>
</table>
</form>
As you can see there are checkboxes and textfields for each record. When I examine the $_POST data from the form it only retains fields for the last record.
Is there a way to pass all this data back to the action?
Cheers,
Jonesy
Use name="chk[]", then PHP will create an array for you.
Change your name arrtibutes to have an opening and closing square brace like this:
name="tags"
name="chk"
to
name="tags[]"
name="chk[]"
This will turn an array like:
$_POST['tags'][0] = VALUE
$_POST['tags'][1] = VALUE
$_POST['chk'][0] = VALUE
$_POST['chk'][1] = VALUE
Yes you can, set brackets at the end of the name value.
E.g.:
<input type="checkbox" name="chk[]" id="'. $product .'">
Then you get an array as result in $_POST['chk'].
Besides that, ids should always be unique. You can give same names, but you should always use different ids.
All of your fields have the same name, when that happens on any form you end up only seeing the last value because it's overwritten by the other fields.
Instead of <input type="checkbox" name="chk" id="124123"> do something like <input type="checkbox" name="chk[124123]" value='1'>
In your code you'd receive $_POST['chk'] as an array of values, only those values that were checked.
you can use as i have given example below. where i have taken one new variable $i = 0; and then you can use this $i into the foreach loop for displaying all product one-by-one..
i think this may help you.
$i = 0;
foreach ($products as $product){
echo '<td><input type="checkbox" name="chk" id="'. $product[$i] .'"></td>';
}
Related
I have been searching on this topic and the more I read the more confused I get. I hope you can help me on this.
My objective is to add checkboxes to a table in order to be able to delete the rows I select from that table. So my code til now is like this:
if ($arch = $pdo->prepare("SELECT name, age FROM table WHERE id = ?)) {
$arch ->execute(array($id));
$data = $arch->fetchAll();
echo '<div class="coolTable" ><table><tr><td>Name</td><td>Age</td><td>Check</td></tr>';
foreach ($data as $row){
echo '<tr>';
foreach ($row as $col){
$col=nl2br($col);
echo '<td>'.$col.'</td>';
}
echo '<td><input type="checkbox" name="checkbox" value="" id="checkbox"></td>';
echo '</tr>';
}
echo '</table></div>';
}
With this, I have all my checkboxes in place. But now, how can I submit the checkboxes with a Post so I can Delete the rows I checked?
I suppose I can use an array to name each checkbox? but don`t know how :-s
Thanks in advance for your help!
Change this line:
echo '<td><input type="checkbox" name="checkbox" value="" id="checkbox"></td>';
with
echo '<td><input type="checkbox" name="checkbox[]" value="" id="checkbox"></td>';
You can access every value of checked checkbox using this array $_POST['checkbox'] if you are using POST method or $_GET['checkbox'] for GET method.
PS: You should give your checkbox's a value.
Hello knowledgeable people. I am having trouble retrieving checkbox data from form. I have a site in which user can add checkboxes themselves, so I am writing them out like this:
<table style="padding:10px;">
<?php
$query_boolean = $DB->prepare("SELECT * FROM moduls WHERE type='boolean'") or die(mysql_error());
$query_boolean->execute();
while (($row = $query_boolean->fetch()) != false)
{
?>
<tr>
<td>
<?php echo $row->name ?>:
</td>
<td>
<?php
$s = "";
$s .= sprintf('<input type="checkbox" class="textbox" name="boolean_%s" value="yes">%s', $row->id, Yes);
$s .= sprintf('<input type="checkbox" class="textbox" name="boolean_%s" value="no">%s', $row->id, No);
echo $s;
?>
</td>
</tr>
<?php
}
?>
</table>
Now I have an advanced search in which I have to chech through every checkbox to see what has been selected (ether none, Yes, No, or both). How can I get the info from every checkbox in variables? Thank you so much!
To get POST data from checkboxes they must have attribute
checked="checked"
EDIT:
If you have 2 checkbox as this..
<input type="checkbox" checked="checked" class="textbox" name="boolean_yes" value="yes">
<input type="checkbox" class="textbox" name="boolean_no" value="no">
When you submit your form the checkbox with attribute checked will be sent as POST and the one without checked attribute will not be sent..
if(isset($_POST['search'])) {
$all_checked = array();
foreach($_POST as $key=>$value){
if(strpos($key, "boolean_") > -1){
$all_checked[$key] = $value;
}
}
var_dump($all_checked);
}
This way you will get inside $all_checked array all marked boxes.. All others checboxes are not marked!
if you want to get checkbox value then use checkbox name as array
<input type="checkbox" name="email1[]" value="">
an get it on another page by
<?php
$var2 = $_POST['email1'];
$v=implode(",",$var2);
echo $v;
?>
try it
I have a form with rows which are populated from a table. Each row has a "checkbox" which the user can check or not.
When the form is submitted I want to be able to read which checkbox have been selected and insert the result in to a data table.
My code so far
FORM:
<form method="post" name="form1" action="<?php echo $editFormAction; ?>">
<table
<?php do { ?>
<tr>
<td>input type="text" name="InspectRoomNo" value="<?php print $row_InspectItems['AuditItemNo']; ?>"></td>
<td>php echo $row_InspectItems['AuditItem']; ?>td>
<td>input name="check[]" type="checkbox" ></td>
</tr>
<?php } while ($row_InspectItems = mysql_fetch_assoc($InspectItems)); ?>
<input type="submit" value="Insert record">
</table>
The insert: fetchs $Items from table
while($row = mysql_fetch_assoc($Items))
{
$array[] = $row['AuditItem'];
}
foreach($array as $id) {
$AuditItemID = mysql_real_escape_string($id);
if(isset($_POST['check'])){
$Checked = mysql_real_escape_string($_POST['check'][$row]);
}
}
The problem I am having is the returned values for all the checkbox is true, even if a checkbox was not selected.
Can anyone help me sort this issue.
Many thanks.
Do it like this:
if(!empty($_POST['check'])) {
foreach($_POST['check'] as $check) {
echo $check;
}
}
You should put the item id inside the checkbox name:
<td><input name="check[<?= $row_InspectItems['AuditItem']; ?>]" type="checkbox" /></td>
Then, you can simply iterate over it:
foreach ($_POST['check'] as $id => $value) {
// do stuff with your database
}
I'm assuming than whomever runs this script is trusted, because it would be easy to forge the list of ids; make sure the current user has permissions to update those records.
What is happening, is that only selected checkboxes get sent to the server, so you will see that your $_POST['check'] array (this is an array!) is smaller than the number of items you have displayed on the screen.
You should add your ID's so that you know what checkboxes got checked and adapt your php processing code to handle an array instead of a single value.
You are also overwriting your InspectRoomNo every row, so you should use an array there as well.
The form side would look something like:
<td><input type="text" name="InspectRoomNo[<?php echo row_InspectItems['AuditItemNo']; ?>]" value="<?php print row_InspectItems['AuditItemNo']; ?>"></td>
<td><?php echo $row_InspectItems['AuditItem']; ?></td>
<td><input name="check[<?php echo row_InspectItems['AuditItemNo']; ?>]" type="checkbox" ></td>
Currently, I have a piece of code which displays four checkboxes and allows a user to select the checkboxes, click submit, and the data, through the POST method, will be sent to the database (called "Spreadsheet") where it would be stored.
Typically, with a radio button, the data stored is only one element. But I noticed that with checkboxes, the elements (for my case specifically) could range from zero to four items. So my issue with my code is, only one element gets stored, even if I press all four. I think I have to store the items as an array, but how do I store + retrieve said items to and from the database?
Below is my code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html> <!-- tells browser this is an HTML document -->
<head> <!-- container of all head elements --> </head>
<body> <!-- Begin the content of the document -->
<?
if (isset($_POST['formSubmit2'])){
$category = $_POST['category'];
$accountID = $_POST['accountID'];
mysql_query("UPDATE Spreadsheet SET category='$category' WHERE accountID='$accountID'");
}
while($row = mysql_fetch_array($query)){
$values = array('0 - Luxury','1 - Brand','2 - Retailer','3 - B2B');
?>
<form name ="category" method ="POST" action ="" >
<?
echo "<input type = 'hidden' name = 'accountID' value = '" . $row['accountID'] . "' >";
for($i = 0; $i < count($values); $i++){
?>
<input type="checkbox" name="category" value="<?php echo $values[$i]; ?>" id="rbl_0" <? if($row['category'] == $i) echo "checked='checked'"; ?>/>
<? echo $values[$i] ?><br>
<? } ?>
<input type ="Submit" name ="formSubmit2" value ="Submit" />
</form>
</body>
</html>
Instead of passing in name="category", set it to "$category[]".
You should be able to retrieve it from $_POST, set it to a new variable, and manipulate it how you want.
if (isset($_POST['formSubmit2'])){
$submitted_category = $_POST['$category'];
$accountID = $_POST['accountID'];
// rest of your code...
}
Hope that helped.
You have to give each checkbox a different name because you are overwriting their values if not.
You can also give them an array name like category[] resulting in something like this:
<input type="checkbox" name="category[]" value="value 1"/> value 1<br/>
<input type="checkbox" name="category[]" value="value 2"/> value 2<br/>
<input type="checkbox" name="category[]" value="value 3"/> value 3<br/>
And then retrieve them with:
$categories = $_GET['category'];
foreach($categories as $category){
echo "Selected " . $category . "<br/>";
}
See as well: How do I create arrays in a HTML ?Docs
You can serialize your array and then store it in a varchar column in your DB
Save:
$values = array(...);
$data = serialize($values);
// Store data in your database
Retrieve:
// $data should come from your DB
$values = unserialize($data);
// Now values holds your array
For sending multiple values in HTTP POST request upon form submission you need to define HTML array.
Please refer the below code snippet
<input type="checkbox" name="category[]" value="0"/>Luxury
<input type="checkbox" name="category[]" value="1"/> Brand
<input type="checkbox" name="category[]" value="2"/> Retailer
<input type="checkbox" name="category[]" value="3"/> B2B
POST values for checkbox will be accessible through superglobal variable $_POST['category']
Here S_POST['category'] will be accessible as an array.
e.g $_POST['category'][0],
$_POST['category'][1],
$_POST['category'][2],
$_POST['category'][3]
So you need to iterate through an array for insertion of individual values for checkbox.
let's say I have a list of checkboxes that the user selects.
<input type="checkbox" name="utility[]" id="utility[]" value="Water" />Water<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />
etc...
The user selected Water and it is added to the database. Now the user wants to update the list:
<input type="checkbox" name="utility[]" id="utility[]" value="Water" checked="checked"/>Water<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />
etc...
How can I check that the utility has already been checked in PHP?
What I've done in the past, to save having hundreds of lines of bloat is this...
First compile all the html in a variable, without any "checked" instances.
$boxes = '';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Water" />Water<br />';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />';
Now I loop over your array of fields to check. I've provided a sample array here too.
$already_checked = array('Water', 'Electricity');
foreach( $already_checked as $ac ) {
$find = 'value="' . $ac . '"';
$replace = $find . ' checked="checked"';
$boxes = str_replace($find, $replace, $boxes);
}
echo $boxes;
You could do something like this:
<input type="checkbox" name="utility[]" value="Water"
<?= in_array('Water', $utilities) ? 'checked="checked"' : '' ?>"
/>
(The $utilities variable above is a stand-in for something like $_REQUEST['utilities'], depending on how your code is structured.)
Like that?
<input type="checkbox" name="utility[]" id="utility[]" value="Water"
<?php
if(isAlreadyChecked("Water"))
echo "checked=\"checked\""
?>
/>Water<br />
<?php
function isAlreadyChecked(value)
{
//Check if it is already checked and return a boolean
}
?>
I tried every variant of the in_array conditional out there and could NEVER get this to work (checking off the checkboxes whose values had been previously selected and thus inserted into the database). I tried complex queries with table joins and no luck with that either. I finally gave up and generated a display:hidden div that opened the array (which for some odd reason I had to IMPLODE rather than explode) and listed its items as comma-separated text. Then I tossed in a little jQuery indexOf() magic to determine if the value of each checkbox was part of said array or not. Took me 10 minutes flat to do this with jQuery, very simple.
Here's some sample code that is live and working fine:
<div class="categories">
<span class="keywords"><?php $categories = array(); $categories = implode(', ', $keywords); echo $categories ?></span>
<em>Please verify category selections with each update.</em><br/>
<?php
include 'db.php';
$sql = mysqli_query($con,"SELECT * FROM categoriesTable ORDER BY Category_Name ASC");
while ($row = mysqli_fetch_assoc($sql))
{
$key = urldecode($row['Category_Name']);
$id = urlencode($row['catID']);
echo "<input type='checkbox' name='Category_Key[]' value='$id' id='cat_$id' $chk> $key<br/>";
}
?>
</div>
CSS sets that div to invisible:
.keywords { display:none; visibility:hidden; }
and the jQuery portion:
$(document).ready(function() {
$('.categories input').each(function(index,data) {
var str=$('.keywords').text();
var catid = $(this).val();
var chk = str.indexOf(catid);
if (chk >= 0) {
$(this).prop('checked', true);
}
});
});
I hope this helps someone else who is stuck wondering why the in_array conditional is failing them. Since this falls in a twilight zone between data and UI regarding data persistence, I think it's a legit route to take. You have one "echo" statement to generate multiple checkboxes (there are around 40 categories in my situation here) and then a simple jQuery .each() to locate what was selected before and render its corresponding boxes as checked.