I have multiple checkbox values stored in a single column in my DB ( Example cat,dogs or dogs,cows etc. it is retrieved as $animals and exploded to compare the values.
$animal_values = explode(",", $animals);
$cat = "cat";
$dogs = "dogs";
$cow = "cow";
foreach($animal_values as $value) {
if( $value == $cat ){
echo '<li>
<input type="checkbox" id="cat" checked="checked" name="animals[]" value="cat" />
<label for="cat">Cat</label>
</li>';
}
if( $value == $dogs ){
echo '<li>
<input type="checkbox" id="dogs" checked="checked" name="animals[]" value="dogs" />
<label for="dogs">dogs</label>
</li>';
}
if( $value == $cow ){
echo '<li>
<input type="checkbox" id="cow" checked="checked" name="animals[]" value="cow" />
<label for="cow">cow</label>
</li>';
}
This way the values that are present shows up as checked checked boxes.
But the thing is I also want to show boxes for whose values are missing as unchecked boxes. How can I achieve this ??
<?php
$animal_value = explode(",", $animal);
echo '<li>
<input type="checkbox" id="cat"';?> <?php if (in_array("cat", $animal_value)) { echo 'checked="checked"'; } ?> <?php echo 'name="animal[]" value="cat" />
<label for="cat">Cat</label>
</li>';
echo '<li>
<input type="checkbox" id="dog"';?><?php if (in_array("dog", $animal_value)) { echo 'checked="checked"'; } ?> <?php echo ' name="animal[]" value="dog" />
<label for="dog">Dog</label>
</li>';
echo '<li>
<input type="checkbox" id="cow"';?><?php if (in_array("cow", $animal_value)) { echo 'checked="checked"'; } ?> <?php echo 'name="animal[]" value="cow" />
<label for="cow">COW</label>
</li>';
?>
Any suggestions for Improvement or any other approach its welcome.
Related
I have a form which has a list of checkboxes to be filled in on insert to database as well as when editing. When editing I am trying to populate the fields with a list of fields from the database which is in the $groups variable and the checked value being checked against the group_id from groups with the group_id from the $user. It is working except it only fills out one checkbox and some users belong to multiple groups. Any ideas, or more efficient ways to do this.
Heres my code so far
<?php foreach($groups as $group) : ?>
<?php foreach ($user['groups'] as $uG) {
if ($uG['group_id'] == $group['id']) {
$checked = "checked";
} else {
$checked = '';
}
}?>
<div class="checkbox">
<label for="group_id-<?php echo $group['id']; ?>">
<input <?php echo $checked; ?> type="checkbox" name="group_id[]" id="group_id-<?php echo $group['id']; ?>" value="<?php echo $group['id']; ?>">
<?php echo $group['name']; ?>
</label>
</div>
<? endforeach; ?>
This problem is that you are searching all the $users['group'] array and not stopping when you find a match, so unless last $uG['group_id'] matches $group['id'] you continue and therefore clear $checked after potentially setting it.
So just add a break when you find a match.
Also, officially the correct way of setting the checked status is checked="checked" although most modern browsers are not that pedantic, its possibly better to stick to the HTML spec
<?php foreach($groups as $group) : ?>
<?php
$checked = '';
foreach ($user['groups'] as $uG) {
if ($uG['group_id'] == $group['id']) {
$checked = 'checked="checked"';
break;
}
}?>
<div class="checkbox">
<label for="group_id-<?php echo $group['id']; ?>">
<input <?php echo $checked; ?> type="checkbox" name="group_id[]" id="group_id-<?php echo $group['id']; ?>" value="<?php echo $group['id']; ?>">
<?php echo $group['name']; ?>
</label>
</div>
<? endforeach; ?>
you could also use a ternary operator and in_array() to do this all in one simple statement
<?php
foreach($groups as $group) :
$checked = in_array( $group['id'], $user['groups'] ) ? 'checked="checked"' : '';
?>
<div class="checkbox">
<label for="group_id-<?php echo $group['id']; ?>">
<input <?php echo $checked; ?> type="checkbox" name="group_id[]" id="group_id-<?php echo $group['id']; ?>" value="<?php echo $group['id']; ?>">
<?php echo $group['name']; ?>
</label>
</div>
<? endforeach; ?>
Define $checked = ''; first then loop and change the value if match found
<?php foreach($groups as $group) : ?>
<?php
$checked = '';
foreach ($user['groups'] as $uG) {
if ($uG['group_id'] == $group['id']) {
$checked = "checked";
}
}?>
<div class="checkbox">
<label for="group_id-<?php echo $group['id']; ?>">
<input <?php echo $checked; ?> type="checkbox" name="group_id[]" id="group_id-<?php echo $group['id']; ?>" value="<?php echo $group['id']; ?>">
<?php echo $group['name']; ?>
</label>
</div>
<? endforeach; ?>
I have set up a group of checkboxes. They are dynamic, so the number of checkboxes will be different dependent on the person using the site. The structure of how the checkboxes are created is:
<label for="plabackformat-holder-label">Format</label>
<div class=" playbackformat-holder-<?php echo $num; ?> playbackformat-holder">
<div class="playback-format-radio-buttons">
<label for="notset-<?php echo $num; ?>">
<input type="checkbox" class="playbackformat-holder-radiobutton" value="notset" name="playback_format[<?php echo $second_num; ?>]" id="notset-<?php echo $num; ?>" <?php if($field['playback_format'] == 'notset') { echo 'checked'; } ?>>None
</label>
<label for="dvd-<?php echo $num; ?>">
<input type="checkbox" class="playbackformat-holder-radiobutton" value="dvd" name="playback_format[<?php echo $second_num; ?>]" id="dvd-<?php echo $num; ?>" <?php if($field['playback_format'] == 'dvd') { echo 'checked'; } ?>>DVD
</label>
<label for="bluray-<?php echo $num; ?>">
<input type="checkbox" class="playbackformat-holder-radiobutton" value="bluray" name="playback_format[<?php echo $second_num; ?>]" id="bluray-<?php echo $num; ?>" <?php if($field['playback_format'] == 'bluray') { echo 'checked'; } ?>>Bluray
</label>
<label for="3d-<?php echo $num; ?>">
<input type="checkbox" class="playbackformat-holder-radiobutton" value="3d" name="playback_format[<?php echo $second_num; ?>]" id="3d-<?php echo $num; ?>" <?php if($field['playback_format'] == '3d') { echo 'checked'; } ?>>3d
</label><br />
</div>
</div>
My save function is:
$new = array();
for ( $i = 0; $i < $count; $i++ ) {
$new[$i]['playback_format'] = $playbackFormats[$i];
}
I've been reading up on this issue and it seems its because my input fields do not contain unique names. I'm trying to store the data into an array, so it would be ['playback_format'] => dvd,3d,bluray or something similar.
Right now its only storing the last checked value. Is there a way I can use a forloop or something to iterate over the checked values and push them into my array??
You can just get rid of the "$second_num" in each <input name="playback_format[]"/> html tag. This will put everything into an array for you once you submit the form. You can check this by adding this line to the page as a test.
<?php print_r($_REQUEST['playback_format']); ?>
Generally, You want to avoid any loop if they aren't required.
Hope that helps with what you are doing.
What is $second_num? Does it need to be a part of the input name?
You can get PHP to recognise the submitted values as an array if you do it this way:
<input name="playback_format[<?php echo $second_num; ?>][]">
Or if you don't need $second_num as part of the name, just:
<input name="playback_format[]">
$_POST['playback_format'] will then be an array containing all the selected options.
There is a section in the PHP docs specifically about this behaviour.
Checkboxes have all the same name in your example. Name it differently like :
<label for="plabackformat-holder-label">Format</label>
<div class=" playbackformat-holder-<?php echo $num; ?> playbackformat-holder">
<div class="playback-format-radio-buttons">
<label for="notset-<?php echo $num; ?>">
<input type="checkbox" class="playbackformat-holder-radiobutton" value="notset" name="playback_format_notset" id="notset-<?php echo $num; ?>" <?php if($field['playback_format_notset'] == 'notset') { echo 'checked'; } ?>>None
</label>
<label for="dvd-<?php echo $num; ?>">
<input type="checkbox" class="playbackformat-holder-radiobutton" value="dvd" name="playback_format_dvd" id="dvd-<?php echo $num; ?>" <?php if($field['playback_format_dvd'] == 'dvd') { echo 'checked'; } ?>>DVD
</label>
<label for="bluray-<?php echo $num; ?>">
<input type="checkbox" class="playbackformat-holder-radiobutton" value="bluray" name="playback_format_bluray" id="bluray-<?php echo $num; ?>" <?php if($field['playback_format_bluray'] == 'bluray') { echo 'checked'; } ?>>Bluray
</label>
<label for="3d-<?php echo $num; ?>">
<input type="checkbox" class="playbackformat-holder-radiobutton" value="3d" name="playback_format_3d" id="3d-<?php echo $num; ?>" <?php if($field['playback_format_3d'] == '3d') { echo 'checked'; } ?>>3d
</label><br />
</div>
</div>
And Try this in PHP :
//WHen you want to see what is send in Post :
var_dump($_POST);
//So, for get result :
$tab = array();
foreach($_POST as $key =>$value){
$tab[$key] = $value;
//Display it
echo $key . "=" . $value;
}
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>";
}
I have this PHP/HTML Code that is selecting data from a MySQL Database:
<?php
$sql3="SELECT * from property_images where property_seq = '".$property["sequence"]."' ";
$rs3=mysql_query($sql3,$conn);
while($property_img=mysql_fetch_array($rs3))
{
?><tr>
<td colspan="2"><img src="http://domain.co.uk/img/property-images/<?php echo $property_img["image"]; ?>" width="80px" height="80px" /></td>
<td colspan="2"><input type="checkbox" name="image1" value="Y" <?php if($property_img["image1"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image2" value="Y" <?php if($property_img["image2"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image3" value="Y" <?php if($property_img["image3"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image4" value="Y" <?php if($property_img["image4"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image5" value="Y" <?php if($property_img["image5"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image6" value="Y" <?php if($property_img["image6"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image7" value="Y" <?php if($property_img["image7"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image8" value="Y" <?php if($property_img["image8"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image9" value="Y" <?php if($property_img["image9"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image10" value="Y" <?php if($property_img["image10"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image11" value="Y" <?php if($property_img["image11"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image12" value="Y" <?php if($property_img["image12"] == 'Y') { echo 'checked="checked"'; } ?> />
<input type="checkbox" name="image13" value="Y" <?php if($property_img["image13"] == 'Y') { echo 'checked="checked"'; } ?> /></td>
</tr><?php
}
?>
each row, has its own image with the columns image1 - image13
i want to update the table with the checkboxes that are checked and unchecked on the form update
how is this possible?
Thanks
If you mean that you want to update the $property_img["imagexx"] val on db depending on the user click on the checkbox you must use ajax.
Fire an event on triggering each checkbox and send the value to a php page that update the php.
Jquery Ajax function can help you on this task.
L
name all your checkboxes images[]
<input type="checkbox" name="images[]" value="1" />
<input type="checkbox" name="images[]" value="2" />
<input type="checkbox" name="images[]" value="3" />
<input type="checkbox" name="images[]" value="4" />
You can then update with PHP :
<?php
$q = "UPDATE property_images SET";
foreach($_POST["images"] as $image) {
$q .= " image" . $image ." = 'Y', ";
}
$q .= " property_seq = '".$property["sequence"]."' WHERE property_seq = '".$property["sequence"]."'";
mysql_query($q);
?>
First of all, mysql_ functions are deprecated, please google mysqli_ or PDO, mysql_ won't be supported on future versions, and is unsafe, etc
Your html output could be much simpler with a loop, also have an eye on putting the sequence number on a hidden field or something first:
<?php
$sql3="SELECT * from property_images where property_seq = '".$property["sequence"]."' ";
$rs3=mysql_query($sql3,$conn);
while($property_img=mysql_fetch_array($rs3)){
?>
<tr>
<td colspan="2"><img src="http://domain.co.uk/img/property-images/<?php echo $property_img["image"]; ?>" width="80px" height="80px" /></td>
<!-- THIS IS VERY IMPORTANT: send the sequence or ID through a hidden field, to know which row you are gonna update later-->
<input type="hidden" name="sequence" value="<?php echo $property_img['sequence']; ?>"/>
<td colspan="2">
<?php for($i = 1; $i <= 13; $i++): ?>
<input type="checkbox" name="images[]>" value="<?php echo $i; ?>" <?php if($property_img["image$i"] == 'Y') { echo 'checked="checked"'; } ?> />
<?php endfor ?>
</td>
</tr>
<?php
}
?>
Then this is the next page where the update is done, have a good look at the comments:
<?php
//Handle as you want the situation when there are no images selected instead of using an exit(), I used it here just for the quickness;
if(count($_POST['images'] < 1) exit('no images where selected to update');
$images = array();
for($i = 1; $i <= 13; $i++){
$string = "image$i = ";
if(in_array($i, $_POST['images'])){
$string .= "'Y'"; //notice the double quoting here, it's important
} else {
//This updates the table so if it was checked when loaded, but unchecked by the user, this makes the change!
$string .= "'N'";
}
}
//This creates a string like: image1 = 'Y', images2 = 'N', etc...
$images = implode(', ', $images );
//try to sanitize the query first ... I won't cos am just showing you your question xD
$sql = "UPDATE property_images SET $images WHERE property_seq = " . mysql_real_escape_string($_POST[sequence]) . ";
mysql_query($sql,$conn);
?>
I post values from check boxes into a database for a user profile. When the user goes to edit his/her profile I want the checkboxes that they selected previously to be checked so they don't lose that info after updating their profile. I have tried many different solutions but with no luck.
The check box values get entered into table name members_teachers into a column called focus and are seperated by a comma for example art,mathematics,dance etc I am not sure how close or far I am away at accomplishing my goal but I greatly appreicate any help or suggestions you can provide. Thank you very much in advance
My code to try and check the values is
<?php
$focusQuery = mysql_query("SELECT focus FROM members_teachers WHERE id = $member_id") or die;
while ($new_row = mysql_fetch_assoc($focusQuery)){
$focusRow = $row['focus'];
$focusValue = explode(',', $focusRow);
foreach($focusValue as $newFocus){
//echo $newFocus;
//echo "<br/>";
$result = mysql_query("SELECT focus FROM members_teachers WHERE focus LIKE '%$focusRow%'") or die;
if(mysql_num_rows($result) > $newFocus){
$checked = 'checked="checked"';
}
else{
$checked = '';
}
}
}
?>
This is my html
<label for="art-focus">Art</label>
<input name="focus[]" type="checkbox" value="Art" <?php echo $checked ?>>
<label for="math-focus">Mathematics</label>
<input name="focus[]" type="checkbox" value="Mathematics" <?php echo $checked ?>>
<label for="dance-focus">Dance</label>
<input name="focus[]" type="checkbox" value="Dance" <?php echo $checked ?>>
<?php
// Create connection
$con=mysqli_connect("hostname","username","pass","dbname");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT focus FROM members_teachers WHERE id = $member_id");
while($row = mysqli_fetch_array($result))
{
$focus=explode(",",$row['focus']);
?>
<input type="checkbox" name="focus[]" value="Art" <?php if(in_array("Art",$focus)) { ?> checked="checked" <?php } ?> >
<input type="checkbox" name="focus[]" value="Mathematics" <?php if(in_array("Mathematics",$focus)) { ?> checked="checked" <?php } ?> >
<input type="checkbox" name="focus[]" value="Dance" <?php if(in_array("Dance",$focus)) { ?> checked="checked" <?php } ?> >
<?php
}
?>
<?php
$focusedValues = array();
$focusQuery = mysql_query("SELECT focus FROM members_teachers WHERE id = $member_id") or die;
while ($row = mysql_fetch_assoc($focusQuery)){
$focusedValues = explode(',', $row['focus']);
}
?>
<label for="art-focus">Art</label>
<input name="focus[]" type="checkbox" value="Art" <?php echo in_array('Art', $checked) ?>>
<label for="math-focus">Mathematics</label>
<input name="focus[]" type="checkbox" value="Mathematics" <?php echo in_array('Mathematics', $checked) ?>
<label for="dance-focus">Dance</label>
<input name="focus[]" type="checkbox" value="Dance" <?php echo in_array('Dance', $checked) ?>
I don't know why you were SELECTing for the second time, that's pointless, you already know what's checked because it's in $focusedValues. Also, in your code, $checked would be empty if nothing was checked and checked="checked" otherwise. You obviously need a variable for each input, no?
<?php $hobby = $row['hobbies'];
$hobbies = explode (' ', $hobby);
?>
<input type="checkbox" name="hobbies[]" value="cricket" <?php echo in_array('cricket', $hobbies?'checked':'') ?> >cricket
<input type="checkbox" name="hobbies[]" value="singing" <?php echo in_array('singing' , $hobbies ?'checked': '') ; ?> >singing
<input type="checkbox" name="hobbies[]" value="football" <?php echo in_array('football', $hobbies ?'checked': '') ; ?> >footballl