Automatcially check checkbox based on database array PHP - php

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']

Related

How can i get array value when i'm on edit page? [duplicate]

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']

show value highest checkbox

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;
}
?>

Dynamic radio button with self-post using PHP & MySQL

I'm drawing data from a MySQL database that dynamically places a question with 4-5 radio button choices for the answer. These radio buttons all belong to the same group, $quest_name. The first pass of the while statement will create 4 radio buttons belonging to radio group "question_1".
It creates 30-40 of these questions on a page, each with 4 radio buttons. I want the user to fill in all there answers and the page to post back to itself with the users answers still selected and then display if they were correct or not (functionality I still have to add).
I'm trying to follow http://www.w3schools.com/php/php_form_complete.asp as an example, but use a dynamically created radio button name instead.
This is what I have thus far:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$quest_num = $row["id"];
$question = $row["question"];
$option_1 = $row["option_1"];
$option_2 = $row["option_2"];
$option_3 = $row["option_3"];
$option_4 = $row["option_4"];
$option_5 = $row["option_5"];
$answer = $row["answer"];
$quest_name = "question_" . $row["id"];
echo "(" . $quest_num . ") " . $question . "<br>";
?>
<label>
<input type="radio" name=<?php echo $quest_name ?>
<?php if (isset(echo $quest_name) && echo $quest_name == echo $option_1) echo "checked"; ?>
value=<?php echo $option_1 ?>><?php echo $option_1 ?>
</label>
<br>
<label>
<input type="radio" name=<?php echo $quest_name ?>
value=<?php echo $option_2 ?>><?php echo $option_2 ?>
</label>
<br>
<label>
<input type="radio" name=<?php echo $quest_name ?>
value=<?php echo $option_3 ?>><?php echo $option_3 ?>
</label>
<br>
<label>
<input type="radio" name=<?php echo $quest_name ?>
value=<?php echo $option_4 ?>><?php echo $option_4 ?>
</label>
<br>
<br>
<?php
}
} else {
echo "0 results";
}
$conn->close();
?>
<input type="submit">
</form>
The part causing me grief so far is:
<?php if (isset(echo $quest_name) && echo $quest_name == echo $option_1) echo "checked"; ?>
I have also tried:
<?php if (isset($quest_name) && $quest_name == $option_1) echo "checked"; ?>
and:
<?php echo (isset($quest_name) && $quest_name == $option_1) ? "checked" : ""; ?>
How do you post back to the same page what they've selected? Like in this case I'm trying to say if "question_1" is set and "question_1" is equal to "converter" (the first radio button option) then have it checked when submit button is clicked.
I'm not that good at web development, but I'm trying to create a website to help my fellow electrical technician classmates.
Thanks for any help.
EDIT :
Using this line of code fixed the issue:
<?php if(isset($_POST[$quest_name]) && $_POST[$quest_name]==$option_1) { echo 'checked="checked"'; } ?>
What you need is called Radio Group. In HTML layer it is created with same name for all and different values for each like this:
<p>
<label>
<input type="radio" name="RadioGroup1" value="Value1" id="RadioGroup1_0">
Radio</label>
<br>
<label>
<input type="radio" name="RadioGroup1" value="Value2" id="RadioGroup1_1">
Radio</label>
<br>
</p>
And when you want to get the user input in php layer you go like this:
<?php
//check if Radio Group 1 is set
if(isset($_POST['RadioGroup1'])) {
// print the value of Radio Group 1 choice
echo $_POST['RadioGroup1'];
}
?>
When you want to create a Selected Radio in HTML layer you go like this:
<input name="RadioGroup1" type="radio" id="RadioGroup1_1" value="radio" checked="checked">
So you have to check if user inputs the value of which radio like this:
<label>
<input type="radio" name="RadioGroup1" value="value1" id="RadioGroup1_0" <?php if(isset($_POST['RadioGroup1']) && $_POST['RadioGroup1']=='value1') { echo ' checked="checked"'; } ?>>
Radio</label>
<br>
<label>
<input type="radio" name="RadioGroup1" value="value2" id="RadioGroup1_1" <?php if(isset($_POST['RadioGroup1']) && $_POST['RadioGroup1']=='value2') { echo ' checked="checked"'; } ?> >
Radio</label>
You could use the following:
<input type="radio" name="<?php echo $quest_name ?>" value="<?php echo $option_1 ?>"
<?php if (isset($quest_name) && ($quest_name == $option_1)) echo "checked"; ?> />

PHP/MySQL mark multiple checkboxes "checked" or not checked based on returned data

Example MySQL query: Returned are two values (Desert and Grasslands.) I'd like to match those two values to checkboxes as "checked" Others will stay unchecked.
My PHP result set:
$row[biome];
<?php
while($row = mysqli_fetch_assoc($selectQueryBiomeResult)) {
echo '<input type="checkbox" name="biomeCheck[]" value="Desert"> Desert';
echo '<input type="checkbox" name="biomeCheck[]" value="Grasslands"> Grasslands';
echo '<input type="checkbox" name="biomeCheck[]" value="Deciduous Forest"> Deciduous Forest';
echo '<input type="checkbox" name="biomeCheck[]" value="Tropical Rainforest"> Tropical Rainforest';
}
?>
Giving a sample code-
<html>
<?php
mysql_connect("host", "username", "pwd") or die("connect error");
mysql_select_db("db_name");
$res=mysql_query("write your query here");
$val_array=array();
while($row=mysql_fetch_array($res))
{
$val_array[]=$row[0];
}
?>
<body>
<input type="checkbox" name="biomeCheck[]" value="Desert" <?php if(in_array("Desert", $val_array)) echo "checked"?>> Desert;
<input type="checkbox" name="biomeCheck[]" value="Grasslands" <?php if(in_array("Grasslands", $val_array)) echo "checked"?>> Grasslands;
<input type="checkbox" name="biomeCheck[]" value="Deciduous Forest" <?php if(in_array("Deciduous Forest", $val_array)) echo "checked"?>> Deciduous Forest;
<input type="checkbox" name="biomeCheck[]" value="Tropical Rainforest" <?php if(in_array("Tropical Rainforest", $val_array)) echo "checked"?>> Tropical Rainforest;
</body>
</html>
If your result is array then try like this
Example Array
$my_array = array(
'first' => 'Desert',
'second' => 'Grasslands',
'third' => 'Deciduous Forest'
);
<input type="checkbox" name="vehicle" value="Desert" <?php if(in_array('Desert', $my_array)) echo( 'checked = "checked"'); ?>/> Desert<br />

PHP - Loop number of selected check boxes on form submit

I have an issue where I need to loop the number of check boxes on a form submit. Foreach check box that is looped I need to then insert data into the database.
How Would I go about looping over the amount of check boxes that have being passed via form submit?
My code is as follows:
Form:
<form action="createChallenge.php" method="post" name="chalCreate">
Challenge Name:<input type="text" name="chalName" />
<br />
Challenge Target:<input type="text" name="chalTarget"/>
<br />
End Date:<input type="text" name="chalDate">
<br />
<!-- Needs a jquery datepicker -->
Select Friends: <br />
<?php
$selFriend = $conn->prepare("SELECT * FROM Friends WHERE UserID = '$userID' AND Friend = 'y' ORDER BY FriendName ASC");
$selFriend->execute();
foreach($selFriend as $row){
?>
<input type="checkbox" name="test" value="<?php echo $row['FriendID'] ?>"><?php echo $row['FriendName'] ?><br>
<?php
}
?>
<br />
<button type="submit">Create Challenge</button>
</form>
PHP to handle the form:
<?php
if(isset($_POST['test']))
{
$i = 0;
foreach($_POST['test'] as $checked)
{
echo $friend = $checked;
$i++;
}
echo $name = $_POST['chalName'];
echo $target = $_POST['chalTarget'];
echo $date = $_POST['chalDate'];
echo $friend = $_POST['test'];
echo $setby = $_COOKIE['userID'];
$create = $conn->prepare("INSERT INTO Challenge ( chalSetBy, chalName, chalTarget, chalDate ) VALUES ('$setby', '$name', '$target', '$date') ");
$create->execute();
if($create)
{
echo "Challenge made successfully";
}
else
{
echo "There was a problem";
}
}
?>
I thought doing the following would echo out data, but it didn't, it only selected the last check box:
$i = 0;
foreach($_POST['test'] as $checked)
{
echo $friend = $checked;
$i++;
}
Make an array of your checkbox in HTML page like as below,
<form name="frm" method="post">
<input type="checkbox" value="1" name="test[]">
<input type="checkbox" value="2" name="test[]">
<input type="checkbox" value="3" name="test[]">
<input type="checkbox" value="4" name="test[]">
<input type="checkbox" value="5" name="test[]">
<input type="checkbox" value="6" name="test[]">
<input type="submit">
</form>
<?php
foreach($_POST['test'] as $key=>$value)
{
echo $value."<br>";
}

Categories