I have a string $eventdays which holds information regarding which days are selected.
The format of the data is:
Monday = Mo
Tuesday = Tu
Wedneday = We
Thursday = Th
Friday = Fr
Saturday = Sa
Sunday = Su
Mo,Tu,We,Th,Fr,Sa,Su
So if for example Tuesday and Friday were selected, the string would be:
Tu,Fr
If Monday, Wednesday, and Saturday were selected it would be:
Mo,We,Sa
Note: Any combination of days can be selected.
I was wondering how to get this information, and preselect checkboxes. The checkboxes are:
<input type="checkbox" name="days[]" value="Mo" />Monday<br />
<input type="checkbox" name="days[]" value="Tu" />Tuesday<br />
<input type="checkbox" name="days[]" value="We" />Wednesday<br />
<input type="checkbox" name="days[]" value="Th" />Thursday<br />
<input type="checkbox" name="days[]" value="Fr" />Friday<br />
<input type="checkbox" name="days[]" value="Sa" />Saturday<br />
<input type="checkbox" name="days[]" value="Su" />Sunday<br />
I know how to preselect a checkbox (checked = "yes"), but my question is how can I parse the string and then select the correct checkboxes from that information?
You can use strpos and dynamically generate your checkboxes.
$eventdays = "Tu,Fr"; // Selected days
$days = array( "Monday" => "Mo",
"Tuesday" => "Tu",
"Wedneday" => "We",
"Thursday" => "Th",
"Friday" => "Fr",
"Saturday" => "Sa",
"Sunday" => "Su"
);
foreach ($days AS $day => $shortDay) {
// Is there an event on this day?
$checked = strpos($eventdays, $shortDay) !== FALSE ? "checked='checked'" : "";
// Generate checkbox HTML
echo "<input type='checkbox' name='days[]' value='{$shortDay}' {$checked} />{$day}<br />";
}
Output
<input type='checkbox' name='days[]' value='Mo' />Monday<br />
<input type='checkbox' name='days[]' value='Tu' checked='checked'/>Tuesday<br />
<input type='checkbox' name='days[]' value='We' />Wedneday<br />
<input type='checkbox' name='days[]' value='Th' />Thursday<br />
<input type='checkbox' name='days[]' value='Fr' checked='checked'/>Friday<br />
<input type='checkbox' name='days[]' value='Sa' />Saturday<br />
<input type='checkbox' name='days[]' value='Su' />Sunday<br />
Assuming your input is a string with line-breaks... First process your data into an keyed array to make life easier... I've used regexes to make it more robust against formatting changes.
$eventdays="Monday = Mo
Tuesday = Tu
Wedneday = We
Thursday = Th
Friday = Fr
Saturday = Sa
Sunday = Su";
$lines = explode("\n", $eventdays);
$data = array();
foreach ($lines as $line) {
if (preg_match("/(\w+)\s*=\s*(\w+)/", $line, $match)) {
$data[] = array('value'=>$match[2], 'label' => $match[1]);
}
}
Now just iterate over the structure printing out the keys / labels. Use the in_array function to check if the current one should be selected. Also I used checked="checked" which is the standards-compliant way of selecting checkboxes... See this question.
$selected_test="Mo,We,Sa";
$select=explode(",", $selected_test);
foreach ($data as $datum) {
$checked="";
if (in_array($datum['value'], $select)) {
$checked = " checked=\"checked\"";
}
echo <<< EOF
<input type="checkbox" name="days[]" value="{$datum['value']}"$checked/>{$datum['label']}<br />\n
EOF;
}
Output
<input type="checkbox" name="days[]" value="Mo" checked="checked"/>Monday<br />
<input type="checkbox" name="days[]" value="Tu"/>Tuesday<br />
<input type="checkbox" name="days[]" value="We" checked="checked"/>Wedneday<br />
<input type="checkbox" name="days[]" value="Th"/>Thursday<br />
<input type="checkbox" name="days[]" value="Fr"/>Friday<br />
<input type="checkbox" name="days[]" value="Sa" checked="checked"/>Saturday<br />
<input type="checkbox" name="days[]" value="Su"/>Sunday<br />
use explode(), it returns an array
$days = "mon,tu";
$needstobeselected= explode(",", $days);
then you have an array with the days that has to be checked. you can then make a loop on the array and write your logic.
i guess crappy method, but build a $checkeddays array, like:
[0] => 'checked',
[1] => ' ',
and so on, then use it :
echo '<input type="checkbox" name="days[]" value="Mo" '.$checkeddays[0].'/>Monday<br />'
the main part is explode.
Related
In the "User Setting" tab of my page, I want the user to determine which types of posts from a specific user. Here is the form:
<form method="post" action="" name="permitted_categories">
Select or deselect which types of Posts that you would like to see.
<p>
<?
$cat_query = mysqli_query($con, "SELECT permitcat FROM permitted WHERE username='$userLoggedIn' AND friendname='$username'")
?>
<label>
<input type="checkbox" name="categories[]" value="Life" id="Life" <? echo $checked;?>>
Life</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="Politics" id="Politics" <? echo $checked;?>>
Politics</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="Entertainment" id="Entertainment" <? echo $checked;?>>
Entertainment</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="Food" id="Food" <? echo $checked;?>>
Food</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="BusFin" id="BusFin" <? echo $checked;?>>
Business/Financial</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="Fitness" id="Fitness" <? echo $checked;?>>
Fitness/Health</label>
<br>
<input type="submit" name="update_categories" id="update_categories">
<?
if(isset($_POST['update_categories'])) {
$permitted_categories = $_POST['categories'];
echo "You will only see the following categories from ". $profile_user_obj->getFirstAndLastName() .": ";
foreach ($permitted_categories as $permcat){
echo $permcat .", ";
}
$values = implode(", ", $permitted_categories);
$permit_query = mysqli_query($con, "INSERT INTO permitted (id, username, friendname, permitcat) VALUES('','$userLoggedIn', '$username', '$values')");
} ?>
</p>
</form>
What I am trying to do is automatically check the boxes where the corresponding values are found in an array.
I have tried several things, but cannot get the code to work.
this is pretty simple.
The HTML documentation:
<input type="checkbox" name="Name" value="Value" id="Id" checked>
If you write "checked" at the end of the input Tag, this will be checked, as word says ;)
Another thing, don't mix tags:
<input type="checkbox" name="Name" value="Value" id="Id" checked>
<label>Life</label>
And finally, your code will work if you make this at the beginning:
$checked = 'checked';
But this will check all boxes, you will need to check something, like this:
<?php $checked = 'checked'; ?>
<input type="checkbox" name="categories[]" value="BusFin" id="BusFin" <?php echo if($something == $otherThing) echo $checked;?> >
<input type="checkbox" name="categories[]" value="Life" id="Life" <?php if($something) { echo "checked"; }?>>
this may vary depending of the array content
here some examples
$assoc_array = [
"life" => "yes",
"food" => "no",
];
if($assoc_array['life'] == "yes"){ echo "checked"; }
$array = [
"life",
"food"
];
if (in_array("food", $array)) {
echo "checked";
}
$assoc_array_bool = [
"life" => "whatever",
"food" => "whatever"
];
if($assoc_array_bool['life']){ echo "checked"; }
// would not check the checkbox
// if you replaced $assoc_array_bool['life'] with $assoc_array_bool['sport']
I have no idea how to calculate total price of this subjects using php.
help me with it.
<div id="mydiv" style="display:none">
<input type="checkbox" name="subject[]" value="biology">biology<br>
<input type="checkbox" name="subject[]" value="physics">physics<br>
<input type="submit" value="Calculate" name="submit" class="wpcf7-submit">
</div>
<div id="mydiv1" style="display:none">
<input type="checkbox" name="subject[]" value="maths">maths<br>
<input type="checkbox" name="subject[]" value="science">science<br>
<input type="submit" value="Calculate" name="submit" class="wpcf7-submit">
</div>
I want to calculate price total of this checkboxes and store it in database with its names using php
php part
if(isset($_POST['subject']))
{
$classes=$_POST['subject'];
$prices = array(
'biology' => 60,
'physics' => 200
);
$sum = array();
$getkeys = array_keys($_POST);
foreach($prices as $key => $value)
{
if(in_array($key, $getkeys)) $sum[] = $value;
}
$ar=array_sum($sum);
echo $ar;
if($classes)
{
$subject = implode(',', $ar);
$query="INSERT INTO feedetails (subjects,price) VALUES ('".$subject."','".$price."')";
if(mysqli_query($conn,$query))
{
echo ("<SCRIPT LANGUAGE='Javascript'>
window.alert('Your fee has been updated.Please proceed to pay.');
window.location.href='payment.php';
</SCRIPT>");
}
}
It appears that your summing strategy was not working, there were numerous issues there including this:
$getkeys = array_keys($_POST);
which appears as an attempt to get the subjects submitted, however they are in their own sub-array of $_POST, i.e. $_POST['subject']
This gets you the summing of the price information you require, however you will need to test your database INSERT code and debug this to ensure you are storing the data required correctly.
if (!empty($_POST['subject'])) {
$prices = [
'biology' => 60,
'physics' => 200,
'maths' => 300,
'science' => 400,
];
$sum = 0;
foreach ($_POST['subject'] as $subject) {
if (!empty($prices[$subject])) {
$sum += $prices[$subject];
}
}
echo '<pre>';
echo '$sum ' . print_r($sum, true);
echo '</pre>';
exit;
// process database inserts here
}
Additionally, when testing your code I notice you had hidden the checkboxes, to resolve this, use the following:
<div id="mydiv">
<input type="checkbox" name="subject[]" value="biology">biology<br>
<input type="checkbox" name="subject[]" value="physics">physics<br>
<input type="checkbox" name="subject[]" value="maths">maths<br>
<input type="checkbox" name="subject[]" value="science">science<br>
<input type="submit" value="Calculate" name="submit" class="wpcf7-submit">
</div>
Try This may be help:
I am not doing all code just you asked for sum part.
Rest you can do Ask if any confusion.
HTML
<form method='post'>
<div id="mydiv" >
<input type="checkbox" name="subject[]" value="biology">biology<br>
<input type="checkbox" name="subject[]" value="physics">physics<br>
<input type="checkbox" name="subject[]" value="maths">maths<br>
<input type="checkbox" name="subject[]" value="social">social<br>
<input type="checkbox" name="subject[]" value="ssc">ssc<br>
<input type="submit" value="Calculate" name="submit"
class="wpcf7-
submit">
</div>
PHP
<?php
$classes =$_POST['subject'];
$prices = array('biology' => 60,'physics' =>
200,'maths'=>100,'ssc'=>40,'social'=>150);
$sum = 0;
echo 'Subject::Price<hr/>';
foreach($classes as $key=>$sub){
if(array_key_exists($sub,$prices)){
echo $sub.'::'.$prices[$sub]."<br />";
$sum = $sum+$prices[$sub];
}
}
echo '<hr/>';
echo $sum;
?>
OUTPUT
In the "User Setting" tab of my page, I want the user to determine which types of posts from a specific user. Here is the form:
<form method="post" action="" name="permitted_categories">
Select or deselect which types of Posts that you would like to see.
<p>
<?
$cat_query = mysqli_query($con, "SELECT permitcat FROM permitted WHERE username='$userLoggedIn' AND friendname='$username'")
?>
<label>
<input type="checkbox" name="categories[]" value="Life" id="Life" <? echo $checked;?>>
Life</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="Politics" id="Politics" <? echo $checked;?>>
Politics</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="Entertainment" id="Entertainment" <? echo $checked;?>>
Entertainment</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="Food" id="Food" <? echo $checked;?>>
Food</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="BusFin" id="BusFin" <? echo $checked;?>>
Business/Financial</label>
<br>
<label>
<input type="checkbox" name="categories[]" value="Fitness" id="Fitness" <? echo $checked;?>>
Fitness/Health</label>
<br>
<input type="submit" name="update_categories" id="update_categories">
<?
if(isset($_POST['update_categories'])) {
$permitted_categories = $_POST['categories'];
echo "You will only see the following categories from ". $profile_user_obj->getFirstAndLastName() .": ";
foreach ($permitted_categories as $permcat){
echo $permcat .", ";
}
$values = implode(", ", $permitted_categories);
$permit_query = mysqli_query($con, "INSERT INTO permitted (id, username, friendname, permitcat) VALUES('','$userLoggedIn', '$username', '$values')");
} ?>
</p>
</form>
What I am trying to do is automatically check the boxes where the corresponding values are found in an array.
I have tried several things, but cannot get the code to work.
this is pretty simple.
The HTML documentation:
<input type="checkbox" name="Name" value="Value" id="Id" checked>
If you write "checked" at the end of the input Tag, this will be checked, as word says ;)
Another thing, don't mix tags:
<input type="checkbox" name="Name" value="Value" id="Id" checked>
<label>Life</label>
And finally, your code will work if you make this at the beginning:
$checked = 'checked';
But this will check all boxes, you will need to check something, like this:
<?php $checked = 'checked'; ?>
<input type="checkbox" name="categories[]" value="BusFin" id="BusFin" <?php echo if($something == $otherThing) echo $checked;?> >
<input type="checkbox" name="categories[]" value="Life" id="Life" <?php if($something) { echo "checked"; }?>>
this may vary depending of the array content
here some examples
$assoc_array = [
"life" => "yes",
"food" => "no",
];
if($assoc_array['life'] == "yes"){ echo "checked"; }
$array = [
"life",
"food"
];
if (in_array("food", $array)) {
echo "checked";
}
$assoc_array_bool = [
"life" => "whatever",
"food" => "whatever"
];
if($assoc_array_bool['life']){ echo "checked"; }
// would not check the checkbox
// if you replaced $assoc_array_bool['life'] with $assoc_array_bool['sport']
I want to find the group of checkbox that user tick the most to something else
please help me!
Thanks.
Here my HTML
<form method="post">
<input type="checkbox" name="group_1[]" value="V1"/>V1
<input type="checkbox" name="group_1[]" value="V2"/>V2
<input type="checkbox" name="group_1[]" value="V3"/>V3
<br>
<input type="checkbox" name="group_2[]" value="V4"/>V4
<input type="checkbox" name="group_2[]" value="V5"/>V5
<input type="checkbox" name="group_2[]" value="V6"/>V6
<br>
<input type="checkbox" name="group_3[]" value="V7"/>V7
<input type="checkbox" name="group_3[]" value="V8"/>V8
<input type="checkbox" name="group_3[]" value="V9"/>V9
<br><br>
<input type="submit" name="submit" />
</form>
PHP
<?php
if (isset($_POST['submit'])) {
$group_1 = count($_POST['group_1']);
$group_2 = count($_POST['group_2']);
$group_3 = count($_POST['group_3']);
if ($group_1 > $group_2 and $group_1 > $group_3) {
echo "Group 1 is highest ";
}
elseif ($group_2 > $group_1 and $group_2 > $group_3) {
echo "Group 2 is highest ";
}
elseif ($group_3 > $group_1 and $group_3 > $group_2) {
echo "Group 3 is highest ";
}
}
?>
i'm new in php so I code "If Else" but i don't want to use this. and one more i don't want to code specific like "$group_1 = count($_POST['group_1']);" i just want to define "name of checkbox" to get value.
all i want is get same result but different code.
I think you could use the max() function to get highest value
Please refer to http://php.net/max
Probably like this:
<?php
if (isset($_POST['submit'])) {
$group_1 = count($_POST['group_1']);
$group_2 = count($_POST['group_2']);
$group_3 = count($_POST['group_3']);
$array = array("Group 1"=>$group_1,"Group 2"=>$group_2,"Group 3"=>$group_3);
$maxIndex = array_search(max($array), $array);
echo $maxIndex;
}
?>
i have the following checkboxes
<input type="checkbox" name="weekday[]" value="Monday" /> Monday
<input type="checkbox" name="weekday[]" value="Tuesday" /> Tuesday
<input type="checkbox" name="weekday[]" value="Wednesday" /> Wednesday </br>
<input type="checkbox" name="weekday[]" value="Thursday" /> Thursday
<input type="checkbox" name="weekday[]" value="Friday" /> Friday
<input type="checkbox" name="weekday[]" value="Saturday" /> Saturday
<input type="checkbox" name="weekday[]" value="Sunday" /> Sunday
I would like to enter all the checked values into "day" field in mysql separated by coma,
please help
How about
implode(',',$_POST['weekday'])
?
if(isset($_POST['submit_btn_name']))
{
$days="";
if(isset($_POST['weekday']))
{
foreach($_POST['weekday'] as $id)
{
$days.=$id.",";
}
$days = substr($days, 0, -1);
}
echo $days;
}
EDIT
this is in response to the comment about the query to post the $days variable as I found it difficult to format code in the comments.
$sql1=mysql_query("INSERT INTO class (class_id, subject_id, student_id, available_days, available_time, status) VALUES ('".$class_id."','".$subject_id."','".$student_id."','".$days."','".$available_time."','pending')")or die('Error: There was error while submitting the schedule, please try again.');
you will get $_POST['weekday'] as an array. you can use it like
$_POST['weekday'][0];
$_POST['weekday'][1];
$_POST['weekday'][2];
$_POST['weekday'][3];
$_POST['weekday'][4];
$_POST['weekday'][5];
$_POST['weekday'][6];
For searching you should implode(',' , $_POST['weekday']) and use
$sql = "select * from table where day in ('" . implode("','" , $_POST['weekday']) . "')";
in sql query
You can do like this:
$arr = array();
// check for CHECKED checkboxes
for(var $i = 0; $i > count($_POST['weekday']); $i++){
// if this checkbox is checked
if (isset($_POST['weekday'][$i])) {
$arr[] = $_POST['weekday'][$i];
}
}
// convert to comma separated
$checkbox_str = implode(',', $arr);
Now you can use $checkbox_str to save in the database.