If choose more than one, the price increases - php

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.

Related

Loop through all check boxes, weather it is checked or unchecked in PHP

My problem is that the below code changes the value of the checked ones, but the index i is assigned to the checked ones only. I want it to pass through all check boxes. For examples if the first and last check boxes were checked, I am getting job[0] is "yes" and job[1] is "yes" and the rest are "no" while I should get "yes" for job[0] and job[4].
Code below:
if(!empty($_POST['job'])){
$i = 0;
$jobArray = array("no","no","no","no","no");
// Loop to store and display values of individual checked checkbox.
foreach($_POST['job'] as $selected){
$jobArray[$i] = "yes";
$i++;
}
} //$_POST['job']
The thing is that checkboxes values exist in your request only if they are checked. You should keep it in mind.
So, you can change your application logic to work with that. But if you really need to have an array with 'yes', 'no' values, just create it.
Let's say you create your checkboxes like so:
<?php for ($i = 0; $i < 10; $i++): ?>
<input type="checkbox" name="job[<?= $i ?>]" value="yes">
<?php endfor; ?>
Then, in your code:
$jobs = [];
for ($i = 0; $i < 10; $i++) {
$jobs[$i] = $_POST['job'][$i] ?? 'no';
}

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

Getting multiple checkbox values in loop

Below is my code
if (!empty($_POST['ok'])) {
$errorMessage = array();
$loopcount = 0;
$i = 0;
foreach ($_POST['theDate'] AS $i => $theDate) {
if ($_POST['EW'][$i] == 'EW') {
$ew = "yes";
} else {
$ew = "no";
}
$i = $i + 1;
echo $ew;
}
}
its pulls the checkbox value of below and assigns it yes or now if value == ew
E/W<input name="EW[]" ID="EW[]" value="EW" type="checkbox" />
the issue is if check these
row checked
1 no
2 yes
3 no
3 yes
the out result when submitted is
row checked
1 yes
2 yes
3 no
4 no
It seems to stick anything checked as ew to the top and I don't get why here is a live working example that when submit is clicked echos with output.... all fields need to be filled but is u just add a number i will work
http://runningprofiles.com/tests/addbet.php
The checkbox is not submitted, if it does not have a value, thus, the 'yes' are the only ones in the loop. the index numbers for that field only from the submitted ones.
edit - clearification: if not checked - it its value does not get submitted.
foreach ($_POST['theDate'] AS $i => $theDate)
You missing the { at the end
like this
foreach ($_POST['theDate'] AS $i => $theDate){

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.

checkbox selection & arrays

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

Categories