Checkbox value equals php variable - php

this may be a redundant question, but i gave up searching for answers already.
My question is, how do I pass in a php variable into the checkbox value.
For an example if I have $theRowID = $row['id'], I want to make the check box value as,
checkbox value ="$theRowID"

If you're generating your HTML in a .php file, you can do it like this:
// assuming you're looping through a query result, also assuming mysqli
$query = mysqli_query('SELECT id FROM tbl');
while ($row = mysqli_fetch_assoc($query)) {
echo '<input type="checkbox" name="foo[]" value="'. $row['id'] .'" />';
}

Related

Insert value of checkbox and number input into database

I tried combining two answers from here:
counting how many checkbox are checked php/html
And here:
validating input types "checkbox" and "number" php/html
My goal is to count how many checkboxes were selected, and insert their values along with the number value in the number input.
I found various other posts about it, but couldn't figure out an answer.
Here is the code:
echo '<form action="" method="post">';
Then I have a for loop, where I create my table rows, with the checkboxes.
Where $id = $row[0] is updated on each loop, which is the id equivalent of my entry.
(The output of
echo '<td style="vertical-align: top;">' . $row[0] . '</td>';
Shows the id correctly)
echo '<tr>';
echo "<td style='vertical-align: top;'><input type='checkbox' name='choice[$id][id]' value='$id'></td>";
echo "<td style='vertical-align: top;'><input type='number' name='choice[$id][order]' size='20'></td>";
echo '</tr>';
echo '<b> <input type="submit" value="Insert"></b>';
Then, on the next page, I have this:
$var_checkbox=$_POST['choice'];
$sql_var_id = "SELECT id FROM custom_form WHERE id=(SELECT max(id) FROM custom_form)";
$var_id_result = mysqli_query($link,$sql_var_id);
$var_id = mysqli_fetch_array($var_id_result);
$count=count($var_checkbox[$var_id[0]]);
for($i=0; $i<$count; $i++){
if($var_checkbox[$i]!= NULL){
$sql1 = sprintf("INSERT INTO custom_form_has_property (custom_form_id,property_id,field_order) VALUES ('%d','%d','%d');",
$var_id[0],
$var_checkbox[$var_id[0]][id],
$var_checkbox[$var_id[0]][order]
);
$result1 = mysqli_query($link,$sql1);
}
}
The problem is, that no values of checkboxes or numbers are inserted.
(As a side note, to try and be more specific)
If instead of matrixes, I use
echo "<td style='vertical-align: top;'><input type='checkbox' name='choice[]' value='$row[0]'></td>";
echo '<td style="vertical-align: top;"><input type="number" name="order[]" size="2"></td>';
And
$var_checkbox=$_POST['choice'];
$order = $_POST['order'];
Then
echo "Orders: $order[0],$order[1],$order[2],$order[3],$order[4],$order[5],$ordemr[6]";
echo "Choices: $var_checkbox[0],$var_checkbox[1],$var_checkbox[2],$var_checkbox[3],$var_checkbox[4],$var_checkbox[5],$var_checkbox[6]";
Will output
Orders: 1,,2,,3,,Choices: 1,3,13,,,,
I need the choiced from the checkboxes to be somehow linked to the orders from the number field. And the only way to achieve that, is if they have the same name, but different indexes, which is why I have the matrix, in the first index, it's saved the id number, which is generated on each loop, and in the second, the actual name, which makes the distinction between them (id and order).
I tried various other things, but it all comes back to the same problem...
The value of order (number) is stored into the array, even when null, while the value of choices (checkbox) doesnt.
I could do an array_filter(), but there is no guarantee that the user will not input an order, while not ticking a choice checkbox.
If I would compare the length of choice with the length of order, after filtered, and if they output the same size, there is still no guarantee, that the user didnt check checkbox of line x, and added a value in the order field, on line y.
Maybe there is a way to pass unchecked values to the choice[] variable as null, the same way it happens in order[]?
What is this? choice[.$id.] ? what are the dots for?
I believe this is the bug!
You probably were trying to concatenate $id into the string before and just forgot to remove them?
Corrected line:
echo "<td style='vertical-align: top;'><input type='checkbox' name='choice[$id][id]' value='$id'></td>";
there are some way to do this ..
you have to count total no of selected check box via jQuery and set those value in hidden field at view page on each check box check or on form submit
you have to take counter on insert part and save the ids and at last update ids value with counter value in database ....

Checkbox to be selected according to database value

I need some help !, I am working on a project where I want to select all those check boxes, which has value fetched from database. Let suppose I have a table which has 4 fields as id, news_title, news_desc and flag. flag field has value like 0 for not checked and 1 for checked. now when I query that table I want only those check boxes which has flag value 1 should be checked and other are not not checked.. How can I do this.. Please Help. Thanks.
Assuming you know how to get the result from mysql you would put the following into your while results loop.
if ($row['flag'] == 1){
echo '<input name="checkbox_name" id="checkbox_id" type="checkbox" checked="yes">';
}else{
echo '<input name="checkbox_name" id="checkbox_id" type="checkbox">';
}
obviously this is just for illustration - there are better ways to do this (like storing $checked = "" or $checked = 'checked="yes"' and the echoing it in-line).
in the HTML it can be checked="yes" or checked
Assuming $row contains your result row, you could use something like:
echo '<input type="checkbox" name="name"' . ($row['flag']==1?'selected="selected"':null) . '/>';

retrieve 1 or more checkbox value from database

this is my html code
<input type='checkbox' name='cbox[]' value='Jaywalking' />
Jaywalking<br>
<input type='checkbox' name='cbox[]' value='Littering' />
Littering<br>
<input type='checkbox' name='cbox[]' value='Illegal Vendor' />
Illegal Vendor
this is my php code
if(isset($_POST['save']))
{
$license_save=$_POST['license'];
$stickerno_save=$_POST['stickerno'];
$fname_save=$_POST['fname'];
$mname_save=$_POST['mname'];
$lname_save=$_POST['lname'];
$no_save=$_POST['no'];
$street_save=$_POST['street'];
$city_save=$_POST['city'];
$bdate_save=$_POST['bdate'];
$violationplace_save=$_POST['violationplace'];
$dd_save=$_POST['dd'];
$mm_save=$_POST['mm'];
$yy_save=$_POST['yy'];
$hh_save=$_POST['hh'];
$min_save=$_POST['min'];
$ampm_save=$_POST['ampm'];
if(is_array($_POST['cbox'])) $violation_save=implode(',',$_POST['cbox']); else $violation_save=$_POST['cbox'];
mysql_query("UPDATE tblcitizen SET license ='$license_save', stickerno ='$stickerno_save', fname ='$fname_save', mname ='$mname_save', lname ='$lname_save', no ='$no_save', street ='$street_save', city ='$city_save', bdate ='$bdate_save', violationplace ='$violationplace_save', dd ='$dd_save', mm ='$mm_save', yy ='$yy_save', hh ='$hh_save', min ='$min_save', ampm ='$ampm_save', violation ='$violation_save', type ='$type_save', officer ='$officer_save', date ='$date_save', ttime ='$ttime_save' WHERE id = '$id'")
or die(mysql_error());
echo "<script>alert('Successfully Edited')</script>";
header("Location: citizen.php");
}
I want to edit some account registered, how can i retrieve 1 or more checkboxes value from the database.
EDITED FOR BETTER ANSWER
if(is_array($_POST['cbox'])) $violation_save=implode(',',$_POST['cbox']); else $violation_save=$_POST['cbox'];
Your query is taking the cbox array, turning it into a string with commas if it is an array (if more than one checkbox was checked), otherwise inserting just one checkbox value with no comma.
To get the values out, just read the string, then compare it with a php strpos()
<?
// Get the checkboxes that were previously selected
$result = mysql_query("SELECT violation FROM tblcitizen WHERE id = '$id'") or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
// put the string into a variable
$mystring = $row['violation'];
}
// use a ternary to determine if this checkbox exists
// if so, make the variable $checked to check the checkbox, otherwise leave it blank
$checked = (strpos($mystring, 'Jaywalking')) ? 'checked' : '';
?>
// write the checkbox to the page. and echo the contents of $checked
// if it was found with strpos() then it will be checked, otherwise it will not be
// <?= ?> is a quick way to echo a variable without the echo command
<input type='checkbox' name='cbox[]' value='Jaywalking' <?=$checked;?> />
I don't quite understand your sentence of "how can i retrieve 1 or more check boxes value from the database" but since I can see your update statement, I am assuming that you want to take the one or more value from the check boxes and update the table in the database.
You will receive the check box value in form of an array
You need to loop through the array and get the value
Store value in one variable and you are good to go to store it in the database
foreach ($cbox as $val) {
$Violation .= $val.",";
}
You can always remove the last comma using PHP substring by the way. Cheers, hope this helps you and anybody out there. Thank You.

How to check a check box if it's value is in DATABASE. PHP

I have inserted some check box values in mysql database using PHP
And in the below image i have fetch the values:
Now i need the o/p like the below image: The values which i inserted in the database should be checked
Hope now its clear.
Thanks in advance..
You should have a table of available options (in this case, something like a cities table), and then a user-to-cities look-up table. Then you can loop over the cities, but also fetch which cities the user has checked.
A sample, without knowing your database structure, would be as follows:
$uid = $_SESSION['user']['id']; // your logged in user's ID
$cities = array();
// get an array of cities
$sql = "SELECT id, name FROM cities";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$cities[$row->id] = $row->name;
}
// get an array of cities user has checked
$sql = "SELECT DISTINCT city_id FROM users_cities WHERE user_id = '$uid'";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$checked[] = $row->city_id;
}
// this would be templated in a real world situation
foreach ($cities as $id => $name) {
$checked = "";
// check box if user has selected this city
if (in_array($checked, $id)) {
$checked = 'checked="checked" ';
}
echo '<input type="checkbox" name="city[]" value="'.$id.'" '.$checked.'/>';
}
If I understand you question properly, the obvious and simplest approach is that you need to fetch records from database and when producing HTML [in a loop ot something similar] check if that value exists in array to results. You haven't given us any examples of your DB structure or code, so you must figure it our yourself how to do it.
Usually, you insert the values into the database. After inserting, you should have access to the same values again. It's not clear how you set up your script, so let's assume you redirect to another script.
What you need to do is retrieve the values for the checkboxes from your database again. Then you know which are selected. This can be used to determine if your checkbox need to be checked or not.
Note:
I assume here that the result of your query is an array with
the selected Ids as a value.
I assume here that your fields are stored in the result of
some query and is basically an array
with Field Id as key and Field Name
as Value.
E.g., something like this:
<?php
// Retrieve values from database.
$resultArray = ... some code ... ;
?>
<?php foreach ($field_types as $field_name => $field_value): ?>
<input type="checkbox" name="<?php echo $field_name; ?>" value="<?php echo $field_value ?>" <?php if (in_array($field_name, $resultArray)) { echo 'checked'; }/>
<?php endforeach; ?>
This results in a checkbox which is checked, if the field_name is inside the result array (with your already checked results). Otherwise they're just rendered as unchecked checkboxes. Hope this is clear enough.

Inserting checkbox values into database

I have a form with several checkboxes which values are pulled from a database.
I managed to display them in the form, assign an appropriate value to each, but cannot insert their values into other database.
Here's the code:
<form id="form1" name="form1" method="post" action="">
<?php
$info_id = $_GET['info_id'];
$kv_dodatoci = mysql_query("SELECT * FROM `dodatoci`") or die('ERROR DISPLAYING: ' . mysql_error());
while ($kol = mysql_fetch_array($kv_dodatoci)){
$id_dodatoci = $kol['id_dodatoci'];
$mk = $kol['mk'];
echo '<input type="checkbox" name="id_dodatoci[]" id="id_dodatoci" value="' . $id_dodatoci . '" />';
echo '<label for="' . $id_dodatoci.'">' . $mk . '</label><br />';
}
?>
<input type="hidden" value="<?=$info_id?>" name="info_id" />
<input name="insert_info" type="submit" value="Insert Additional info" />
</form>
<?php
if (isset($_POST['insert_info']) && is_array($id_dodatoci)) {
echo $id_dodatoci . '<br />';
echo $mk . '<br />';
// --- Guess here's the problem ----- //
foreach ($_POST['id_dodatoci'] as $dodatok) {
$dodatok_kv = mysql_query("INSERT INTO `dodatoci_hotel` (id_dodatoci, info_id) VALUES ('$dodatok', '$info_id')") or die('ERROR INSERTING: '.mysql_error());
}
}
My problem is to loop through all checkboxes, and for each checked, populate a separate record in a database.
Actually I don't know how to recognize the which box is checked, and put the appropriate value in db.
You can tell if a checkbox is selected because it will have a value. If it's not selected, it won't appear in the request/get/post in PHP at all.
What you may want to do is check for the value of it and work based on that. The value is the string 'on' by default, but can be changed by the value='' attribute in HTML.
Here are a couple snippets of code that may help (not exactly production quality, but it will help illustrate):
HTML:
<input type='checkbox' name='ShowCloseWindowLink' value='1'/> Show the 'Close Window' link at the bottom of the form.
PHP:
if (isset($_POST["ShowCloseWindowLink"])) {
$ShowCloseWindowLink=1;
} else {
$ShowCloseWindowLink=0;
}
.....
$sql = "update table set ShowCloseWindowLink = ".mysql_real_escape_string($ShowCloseWindowLink)." where ..."
(assuming a table with a ShowCloseWindowLink column that will accept a 1 or 0)
As an extra note: You're using the wrong HTML syntax for IDs and <label>. <label>'s "for" attribute should point to an ID, not a value. You also need unique IDs for each element. The code you have posted would not validate.
Also, you're not validating your code at all. At the very least, do a htmlspecialchars() or htmlentities() on the input before you output it and a mysql_real_escape_string() before you insert data into the DB.
2nd Answer:
You might do something like this:
HTML:
echo '<input type="checkbox" name="id_dodatoci[]" value="'.$id_dodatoci.'" />';
PHP:
if ( !empty($_POST["id_dodatoci"]) ) {
$id_dodatoci = $_POST["id_dodatoci"];
print_r($id_dodatoci);
// This should provide an array of all the checkboxes that were checked.
// Any not checked will not be present.
} else {
// None of the id_dodatoci checkboxes were checked.
}
This is because you are using the same name for all of the checkboxes, so their values will be passed to php as an array. If you used different names, then each would have it's own post key/value pair.
This might help too:
http://www.php-mysql-tutorial.com/php-tutorial/using-php-forms.php
This is the loop that I needed. I realized that I need a loop through each key with the $i variable.
if(isset($_POST['id_dodatoci'])){
$id_dodatoci=$_POST['id_dodatoci'];
$arr_num=count($id_dodatoci);
$i=0;
while ($i < $arr_num)
{
$query="INSERT INTO `dodatoci_hotel`(id_dodatoci,info_id)
VALUES ('$id_dodatoci[$i]','$info_id')";
$res=mysql_query($query) or die('ERROR INSERTING: '.mysql_error());
$i++;
}
}
Well, as Eli wrote, the POST is not set, when a checkbox is not checked.
I sometimes use an additional hidden field (-array) to make sure, I have a list of all checkboxes on the page.
Example:
<input type="checkbox" name="my_checkbox[<?=$id_of_checkbox?>]">
<input type="hidden" name="array_checkboxes[<?=$id_of_checkbox?>]" value="is_on_page">
So I get in the $_POST:
array(2){
array(1){"my_checkbox" => array(1){[123]=>"1"}}
array(1){"array_checkboxes" => array(1){[123]=>"is_on_page"}}
}
I even get the second line, when the checkbox is NOT checked and I can loop through all checkboxes with something like this:
foreach ($_POST["array_checkboxes"] as $key => $value)
{
if($value=="is_on_page")
{
$value_of_checkbox[$key] = $_POST["my_checkbox"][$key];
//Save this value
}
}
Also something that few people use but that is quite nice in HTML, is that you can have:
<input type="hidden" name="my_checkbox" value="N" />
<input type="checkbox" name="my_checkbox" value="Y" />
and voila! - default values for checkboxes...!

Categories