checkbox selection & arrays - php

I have 9 check boxes in my select.php
<form method="post" action="test.php">
<input type="checkbox" name="g1[]" id="c1" value="c1">
<input type="checkbox" name="g1[]" id="c2" value="c2">
<input type="checkbox" name="g1[]" id="c3" value="c3">
<input type="checkbox" name="g2[]" id="h1" value="h1">
<input type="checkbox" name="g2[]" id="h2" value="h2">
<input type="checkbox" name="g2[]" id="h3" value="h3">
<input type="checkbox" name="g3[]" id="d1" value="d1">
<input type="checkbox" name="g3[]" id="d2" value="d2">
<input type="checkbox" name="g3[]" id="d3" value="d3">
</form>
ok my test.php looks like this now:
error_reporting(E_ALL);
$g1 = $_POST['g1'];
$g2 = $_POST['g2'];
$g3 = $_POST['g3'];
//Connect to DB
$ng1 = count($g1);
$ng2 = count($g2);
$ng3 = count($g3);
$sum = 0;
for ($i = 1; $i <= 3; $i++)
{
$arr = "g$i";
if (!isset($_POST[$arr]))
${$arr} = array();
else
${$arr} = $_POST[$arr];
if (!is_array(${$arr}))
die("Error in input parameter $arr");
${"ng$i"} = count(${$arr});
if (${"ng$i"} < 1)
die("At least one $arr checkbox must be checked");
$sum += ${"ng$i"};
${"g$i"."_sql"} = implode(',', array_map(${$arr}, 'mysql_real_escape'));
}
$query="INSERT INTO ch_lg (g1, g2, g3) VALUES ('$g1_sql','$g2_sql','$g3_sql')";
mysql_query($query) or die(mysql_error());
mysql_close();
//echo message
}
Modifid Question
I need to check that:
The user chose 1 checkbox from each array (your code does this)
He didn't select more than 4 checkboxes (your code does this)
He chose 1 more checkbox from JUST one array (meaning that he has to chose 4 in total and that just 1 of each is not acceptable) - I think this is not happening in your code. Does it?
Thank you

"No more than 3 in both of them" means that 2 hair + 1 color is OK, but 2 hair + 2 color is not because it would give 4? Then:
$ncolor = count($color);
$nhair = count($hair);
if (($ncolor >= 1) && ($nhair >=1) && (($ncolorn+$nhair)<=3))
// OK
else
// No good.
and then insert my values into db columns COLOR / HAIR.
You have to explain how your DB is structured and how do you want the data. If I get 2 hair and 1 color, do you want:
3 rows, one with color, two with hair
2 rows, one with color and hair, one with hair alone
1 row with colors and hairs coalesced with separators:
$color_sql = implode(',', array_map($color, 'mysql_real_escape'));
$hair_sql = implode(',', array_map($hair, 'mysql_real_escape'));
INSERT INTO mytable (..., color, hair, ...)
VALUES (...,'$color_sql','$hair_sql', ...);
Also, at the beginning of test.php I assume there is something like:
<?php
error_reporting(E_ALL);
$g1 = $_POST['g1'];
$g2 = $_POST['g2'];
$g3 = $_POST['g3'];
...
Verification could be done in a cycle:
<?php
error_reporting(E_ALL);
$sum = 0;
for ($i = 1; $i <= 3; $i++)
{
$arr = "g$i";
if (!isset($_POST[$arr]))
${$arr} = array();
else
${$arr} = $_POST[$arr];
if (!is_array(${$arr}))
die("Error in input parameter $arr");
${"ng$i"} = count(${$arr});
if (${"ng$i"} < 1)
die("At least one $arr checkbox must be checked");
$sum += ${"ng$i"};
${"g$i"."_sql"} = implode(',', array_map(${$arr}, 'mysql_real_escape'));
}
// NOTICE: 'NULL' between quotes? Should't it be NULL without quotes?
// If ID is autoincrement, just omit it: (g1, g2, g3) VALUES ('$g1_sql',...)
$query="INSERT INTO ch_lg (ID, g1, g2, g3) VALUES ('NULL','$g1_sql','$g2_sql','$g3_sql')";
mysql_query($query) or die(mysql_error());
mysql_close();

Related

If choose more than one, the price increases

I'm working on a project. My codes are simply written below
HTML
<input type="checkbox" name="A" value="A">A
<input type="checkbox" name="B" value="B">B
<input type="checkbox" name="C" value="C">C
<input type="submit" name="submit" value="Submit">
PHP
<?php
$price=0;
if(isset($_POST["submit"])){
//the code goes here
}
?>
If only one of the option is chosen, it's free (no price). But, if the user chooses more than one, the $price is +10 in every option. So, it can be illustrated like this
Choose 1 = free
Choose 2 = +10
Choose 3 = +20
I have no idea with my PHP and the line //the code goes here is still empty. Any idea?
Homework, huh? I didn't even have to go to college for that one.
<?php
if( isset($_POST) )
{
$count = 0;
$arr = [
array_key_exists('A', $_POST),
array_key_exists('B', $_POST),
array_key_exists('C', $_POST)
];
for( $i = 0; $i < 3; $i++ ) {
if( $arr[$i] ) $count++;
}
// Now count the total - 1 and * it by 10
if( $count > 1 ) $total = ($count - 1) * 10;
}
Basically this script will check for the key in the $_POST array, if you do not select a checkbox it would not create the key for _POST array and thus it would be false.
If it's false then just skip by default. However, if it's true, it will increment to the $count variable. Then if $count is greater than one than we add create a new variable of $total = $count - 1. That will remove one value from $count then times it by 10.

access element with variable name

I have a checkbox table declared like this:
for ($x = 0; $x < 6; $x++) {
echo "<tr>";
echo "<td>"; echo $days[$x]; echo '</td>'; //displays days
echo '<td><input type="checkbox" name="check_list[]" onClick="toggle(this, '.$x.')" value="1"/> All';
echo '<input type="hidden" name="check_list[]" onClick="toggle(this, '.$x.')" value="0"/></td>'; //creates check all buttons
for ($y = 0; $y < 12; $y++){
echo '<td><input type="checkbox" name="'.$x.'" value="1"> Bar 1<br/></td>'; //creates the other buttons
}
echo "</tr>";
}
The name="check_list[]" checkbox selects all the checkboxes in the same row when checked. It is done with this script:
<script language="JavaScript">
function toggle(source, id) {
checkboxes = document.getElementsByName(id);
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
Then the data are stored like this in the database:
<?php
$i=0; $store[20]; $check[20];
foreach($_POST['check_list'] as $value){
$store[$i] = $value; $i= $i + 1;
}
$check = str_split(preg_replace('/10/','1',implode('',$store)));
array_walk($check, 'intval');
if($check[0]) { $monday = 1; } if(!$check[0]) {$monday = 2; }
if($check[1]) { $tuesday = 1; } if(!$check[1]) {$tuesday = 2; }
if($check[2]) { $wednesday = 1; } if(!$check[2]) {$wednesday = 2; }
if($check[3]) { $thursday = 1; } if(!$check[3]) {$thursday = 2; }
if($check[4]) { $friday = 1; } if(!$check[4]) {$friday = 2; }
if($check[5]) { $saturday = 1; } if(!$check[5]) {$saturday = 2; }
?>
Obviously, this is not the whole code (I wrote the sql query to connect and insert the variables for the days. And it worked). But till now I am only taking the values of the first checkbox for each row. Which means that if I check it, all the checkboxes of that row are checked. But I am only reading the fact that all the checkboxes of that row are checked. If I only check a normal checkbox in a row, its value is not posted and I the only info stored is that not all checkboxes are checked (represented by value 2).
What I want to do is take the value of the normal checkboxes for each row instead, and concatenate them in a number. For example, for monday checkboxes (checked, unchecked, unchecked, checked) i would store $monday = 1221.
The same must be done for all days (monday to saturday)
You can do as follows:
for ($y = 0; $y < 12; $y++){
<input type="text" name="matrix['.$x.']['.$y.']" value="Text" />
}
And in your sever:
foreach($_POST['matrix'] as $key => $value) {
echo $key;// Value of $x
foreach($value as $k => $val) {
echo $k;// This would be the value of $y
echo $val;// This would be the value of the inputs
}
}
The way you describe it, it is not possible. It is not possible to put an array declaration as a variable name. However, I somewhat get (and assume) a picture of what you want to do.
After creating the input elements dynamically, also create a hidden input element that contains the "count" of how many elements where created. Then, in PHP code, first access the count element to find out how many elements are present. Then, loop through that index, to build the loop name for each element and access their values.
I appreciate the suggestions given, but I actually tried an alternative solution. Instead of referring to the elements by name or id, I refer to them by class and by name. I use the class (variable) to do the toggle function and the name (which is a one dimensional array) to get their values.
In short, this is the general idea of the code:
The checkbox declaration
echo '<td><input type="checkbox" class="'.$x.'" name="check_list[]" value="1"> <br/>';
The toggle function:
function toggle(source, id) {
checkboxes = document.getElementsByClassName(id);
for(var i=0, n=checkboxes.length;i<n;i++) {checkboxes[i].checked = source.checked;}
}
The php code to get the values:
$i=0; $unclean[180];
foreach($_POST['check_list'] as $value){
$unclean[$i] = $value; $i= $i + 1;
}
Then, knowing the dimensions the matrix had, i simply separate this one dimensional array into an array of one dimensional arrays (basically a matrix) iterating through it with a for loop

Loop through form to update SQL Database

I am building a page that writes out a varying number of categories and then, under each category, writes out the units associated with that category. Each category section is a single form with fields that are repeated and named according to what row they belong to. The layout is like this:
Category 1
Unit 1 Update Fields
Unit 2 Update Fields
Unit 3 Update Fields
Submit Button for Category 1
etc.
Each field is named the same thing with the unit number added on the end:
Features1, Features2, Features3, etc.
The total number of rows in a given category is held in the variable $id# where # is the category's ID (ex: $id1, $id2, $id3, etc).
I've got most of this sorted out. However, I want to loop through and perform a SQL query if the form has been changed, and that's where I'm having trouble. At this point, I'm at a loss. Here is a simplified version of my code:
if (isset($_POST['submit'])) {
$form = $_POST['form']; //save which category we're on in a variable.
for ($i = 1; $i <= ${id.$form}; $i++) { //I think the problem is here
$Feature = $_POST['Feature'.$i];
$update = "UPDATE Units
SET Feature ='$Feature'
WHERE ID='$i'";
if (($Feature!=${initialFeature.$i})) {
$updateQuery = mysqli_query($dbc, $update);
}
}
}
How can I make this work? Is there a better way to do this?
The way I would do it is using an array in field names.
<input type="text" name="id[]" value="$foo">
Then on the action page for the form
$id = $_POST['id'];
for($i=0;$i<sizeof($id),$i++){
...//do something here using $id[$i] to select elements in the array
}
I think that is what you're trying to do.
try this
for($i=0; $i<3; $i++)
echo '<input type="text" name="feature[]" value=""/>';
echo '<input type="submit" name="go" value="submit">';
if (isset($_POST['go'])) {
$feature = $_POST['feature'];
if(is_array($feature)){
for ($i = 1; $i <= count($feature); $i++) {
$update = "UPDATE Units
SET Feature ='$feature[$i]'
WHERE ID='$i'";
$updateQuery = mysqli_query($dbc, $update);
}
}else{
$update = "UPDATE Units
SET Feature ='$feature'
WHERE ID='$i'";
$updateQuery = mysqli_query($dbc, $update);
}
}
hope this code can solve your problem

How to select mysql columns to insert multiple check box values using for loop

I have 3 checkboxes:
<input name="perm[0]" type="checkbox" value="1" />
<input name="perm[1]" type="checkbox" value="1" />
<input name="perm[2]" type="checkbox" value="1" />
Im using a for loop to iterate through the array as follows:
for($i=0; $i < 3; $i++)
{
$perm[$i] = isset($_POST[$perm][$i]) ? 1 : 0;
}
Earlier I created the 3 columns successfully uread, uwrite and usearch.
i would like to insert the data from perm[0] into uread,perm[1] into uwrite and so on,i don't know how to do that using a single INSERT statement.
Thanks in advance.
$uread = 0;$uwrite = 0; $usearch = 0;
if(isset($_POST[perm[0]])==1)
$uread = 1;
if(isset($_POST[perm[1]])==1)
$uwrite = 1;
if(isset($_POST[perm[2]])==1)
$usearch = 1;
Insert into `your-tbl-name`(uname,uwrite,usearch) values ($uread,$write,$usearch);
From brief information you have provide,I expect this may fulfill your requirement
$uread = 0;$uwrite = 0; $usearch = 0; // User have not checked any thing and 0=unchecked,1=checked
if(isset($_POST[perm[0]]))
$uread = 1;
if(isset($_POST[perm[1]]))
$uwrite = 1;
if(isset($_POST[perm[2]]))
$usearch = 1;
//NOW insert statement
Insert into `your-tbl-name`(uname,uwrite,usearch) values ($uread,$write,$usearch);
Modify insert statement according to your requirement.

php/mysql two variable array

I am allowing user to create up to ten categories using text boxes in a form. To do this I have ten textboxes in the form with name = cat[]. The first time they enter categories--however many, up to ten, on the receiving end, I just collect the array of categories and save them to a table of categories using an insert statement. So far so good.
However, now I want to let them change categories they already set or add extras up to ten total. The categories they already set have ids. So I echo the ids to the form along with the category names. My problem is how do I collect the names and ids now? New ones need to be inserted and existing ones may need to be updated in the table? For some reason, I'm at a total loss how to do this. This is what I have so far>
Table Cats
id | catname | userid
Form page:
//retrieve existing cats if any...also get catids
echo '<form action = storecats.php method=post>';
$i=1;
//Get all existing cats
while($row = mysql_fetch_array($res))
{
$catname = $row['catname'];
$catid = $row['id'];
echo '<input type = "text name="cat[]" value="'.$catname.'">Cat 1';
echo '<input type="hidden" name="id[]" value = "'.$catid.'">';
$i = $i+1;
}
//empty boxes up to ten.
while($i <= 10){
echo '<input type="text" size=18 name="cat[]" value=""> Cat '.$i.'<br>';
$i = $i+1;
}//end appending of blank categories
echo '<input type="submit" name="submit" value="submit"></form>';
On receiving end, I can collect the array for cat and id.
$idarray = $_POST['id']; //there will be as many elements as there were ids
$catarray = $_POST['cat']; //there will be ten elements in array
Where there is an id, I want to perform an update whereas where there is no id I want to insert unless the value is blank.
My problem is I can't figure out how to link the id and the cat names being received in the different arrays. Note, there will always be ten cat names but there will only be as many ids as were in the table for that user previously.
You can do it with 2 array on HTML side:
$x=0;
while ($row = mysql_fetch_array($res))
{
echo '<input type="text" name="updateCat['.$row["id"].']" value="'.$row["catname"].'"> Cat Name';
$x++;
}
// new ones
for(;$x<10;$x++)
{
echo '<input type="text" name="newCat[]">';
}
and on php side:
// update old categories
foreach ($_POST["updateCat"] as $key => $value)
{
mysql_update ("UPDATE table SET name = $value WHERE id = $key");
}
// insert
foreach ($_POST["newCat"] as $value)
{
mysql_update ("INSERT INTO table {...}");
}
You have also check that there are not more than 10 Categories when inserting new ones.
Name the inputs which are for existing categories cat_update[] and name inputs which are for new categories cat_insert[]. When you process the form data with PHP you have three arrays:
$ids = $_POST['id']; // Ids for update
$update = $_POST['cat_update']; // Values for UPDATE
$insert = $_POST['cat_insert']; // Values for INSERT
for($i = 0; $i < count($ids); $i++) {
//Execute 'UPDATE `table` SET `value` = $update[$i] WHERE `id` = $ids[$i]
}
for($i = 0; $i < count($insert); $i++) {
//Execute 'INSERT INTO `table` (`value`) VALUES ($insert[$i])
}
I'm not sure I get it, but you could simply give different names to the two sets of categories.
In your second loop putting 'name = "new_cat[]"' will allow you to distinguish between modified categories ('$_POST[cat]') and new ones to be inserted ('$_POST[new_cat]') in your receiving storecats.php code.

Categories