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.
Related
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 ....
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) . '/>';
I have an array of checkboxes.
<input type="checkbox" name="selection[]" value="move" />
<input type="checkbox" name="selection[]" value="move2" />
<input type="checkbox" name="selection[]" value="move3" />
<input type="checkbox" name="selection[]" value="move4" />
Depending on the number of checkboxes selected, a table with corresponding number of rows is generated.
for($x=0; $x<$N; $x++)
{
echo nl2br("<td><textarea name=art[] rows=10 cols=30></textarea> </td><td><textarea name=science[] rows=10 cols=30></textarea></td></textarea></td><td><textarea name=method[] rows=10 cols=30></textarea></td><td><textarea name=criteria[] rows=10 cols=30></textarea></td></tr>");
}
I cannot tell how many table rows with corresponding columns will be generated each time. So how to write the code to insert each set of row array is a problem. I have tried the
$optionsVal = implode(",", $data);
but that only works to store the selected options and not for the generated table rows and columns.Please can anyone help with this. Thanks in advance
Okay so I think I understand a little better, but perhaps you should relay your question in other terms.
Basically my understanding is that you are accepting an uncertain (within the boundaries of the number of checkboxes you have) number of checkboxes, which there in turn generate a row for each selected check box.
If you want to store these generated rows in mySQL you need to post the data back to the database
$result = mysqli_query($query, $conn);
$row = mysqli_fetch_array($result);
You need to set a $result similar to this, and store your check box values in it
In this example if the end-user hits the save button it inserts the values from the check box into a variable
if(isset($_POST["savebtn"]))
{
//inserting the new information
$id = $_POST[""];
$name = $_POST[""];
//iterate through each checkbox selected
foreach($_POST["checkbox"] as $loc_id)
{
$query = "INSERT INTO table(ID, Loc_Code) VALUES('$id', '$loc_id')";
$result = mysqli_query($query, $conn);
}
?>
This was just kinda taken from another example, but you are way off with the implode, you need to save the results of the php selection to variables first, and then assign them rows in mySQL by looping through the selection
UPDATE:
Okay, so you got them in an array, seelction[] - this is good now you would want to check to see if a certain value is selected...
if (in_array("move2", $_POST['selection'])) { /* move2 was selected */}
then you want to put that into a single string - you were right with the implode method
echo implode("\n", $_POST['selection']);
then echo it out with a foreach loop
foreach ($_POST['selection'] as $selection) {
echo "You selected: $selection <br>";
}
In short form, users have checkbox values stored in a MySQL database. I can loop through the database to display the VALUES (Skills_ID + Skills_Name) for each checkbox so the user can add their skills; however, I'm not able to populate these checkboxes with the default value marked "checked" for those skills already in the database.
A box full of karma for anyone who can help me get to bed tonight. :)
Here is my code:
function isChecked() {
$query = "select * FROM individual_skills WHERE Ind_ID = ".$_SESSION['Ind_ID']. "";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
// If value exists, set $valueExitsInDB to true
if (isset($row['Skills_ID'])) {
$valueExitsInDB="TRUE";
} else {
$valueExitsInDB="FALSE";
}
// if the value does exist, then we are writing 'checked' in the checkbox
if ($valueExitsInDB) {
return "checked";
} else {
return "";
}
} // END WHILE LOOP
} // END FUNCTION
And, my code within the checkbox loop looks like this (no need to burden you with reading the loop as I can safely pull the checkbox values to the output -- just not the default value):
echo "<input type='checkbox' name='skills[]' value='$skill_ID' checked='isChecked()'>". $skillName ."";
So, you can see, I'm calling the function with: isChecked().
Any, and all help, very much appreciated.
There are a couple of problems with your code, assuming I understand what you are trying to do:
You are not actually calling the function isChecked() as you believe; it is simply the string "isChecked()" being added to the output. If you checked the resulting HTML you would notice this. The line should read:
echo "<input type='checkbox' name='skills[]' value='$skill_ID'" .
(isChecked($skill_ID) ? " checked='checked'" : "") . "'> $skillname";
As you notice above, you should pass the skill ID to the isChecked() function. You should then check this row in the query, not *whether there is any Skills_ID set in the returned query. Otherwise you are checking whether any skill is defined for that individual! So your function should now read:
function isChecked($skill_ID)
{
$query = "SELECT 1 FROM individual_skills WHERE Ind_ID = " .
$_SESSION['Ind_ID'] . " AND Skills_ID = $skill_ID";
$result = mysql_query($query) or die(mysql_error());
return mysql_num_rows($result) = 1;
}
A couple of side notes:
I am returning either a false or true value from the function. This is in line with the naming "is..." which will return a yes or no. The caller (the echo statement) can then decide what to do with the returned value.
You probably don't have to hit the database 1000 times like you are doing now. If you change your initial query to include an isChecked column you won't need the function and additional queries in the first place.
It should be something like below.
Method 1
echo "<input type='checkbox' name='skills[]' value='$skill_ID' checked='".isChecked()."'>". $skillName ."";
Method 2
you can just try
echo "<input type='checkbox' name='skills[]' value='$skill_ID ".isChecked().">". $skillName ."";
Explanation
Method 1
checked="checked"
should be a different attribute rather than putting it into the value
Method 2
Also addding just checked would do the trick for you too.
Advice
Rather than making a database call for each check box try to make an array that would contain all the data for you. Try muti-dimensional array.
echo "<input type='checkbox' name='skills[]' value='$skill_ID'" . isChecked() . ">" . $skillName . "";
Try to use this
i think ,your error(all checked checkboxes) is because of isset,instead of isset($row['Skills_ID']) use !empty($row['Skills_ID']) or !is_null($row['Skills_ID']) because if the field is null then also it will give you true,
see here link
I'm working on a homework assignment that involves PHP. Basically, I have a page that contains a web form that renders items pulled from a database. There's checkboxes on each row and 2 radio buttons. The user selects "accept" or "deny" and when submit is clicked, the items that are checked are supposed to change to that approval status. All of the items in the form are submitted into post. I thought that post is an array so I could just use a while loop with a counter so that the loop traverses through the array and when it gets to the last index (which should contain approve or deny). A query is generated that changes all of the previous indexes to approve or deny. I'm sorry if this isn't making much sense.
Here's a picture for more clarification
Here's the code I used to generate the webform:
<?php
#create a query string
$query = "SELECT * FROM Request WHERE superemail = '$user'";
#echo $query;
#run the query
$result = mysqli_query($link, $query) or die('error querying');
while($row = mysqli_fetch_array($result)){
#print out each row of the queryi
#line up the query results with temporary strings
$change = $row['KEY'];
$name = $row['first']. " " . $row['last'];
#echo $name;
$email = $row['email'];
#echo $email;
$type = $row['type'];
#echo $type;
$duration = $row['duration'];
$status = $row['status'];
#create a table row with the query results
echo "<tr><td><input type=checkbox name=$change /></td>
<td>$name</td>
<td>$email</td><td>$type</td>
<td>$duration</td><td>$status</td></tr>";
} #end while
?>
<label for=update>Change status to:</label><br />
<input type=radio name=update value=A />Approved<br />
<input type=radio name=update value=D />Denied<br />
<input type = submit value = "Change Status" />
Each input tag (your checkboxes and your radio button) in your html should have a name attribute, such as: <input type='radio' name='accept' value='1' />. When the form is submitted and processed by PHP, your script will be able to access that info at $_POST['accept'] (or $_GET['accept'] depending on the form's method).
So you should be able to specify a name for the radio button, then check to see if there is a value in the POST array at that index.
I am going to assume a few things. First, that it is a design goal of yours to only process items in your approval queue that you choose to select, leaving the others alone. Second, that you want to change their status to what is chosen in a radio button. Third, that you want both a code snippet and an explanation as to how the task got accomplished.
So, here goes.
You have a series of checkboxes; I assume they have the same name. If you wish for the values to be passed to PHP as an array, you absolutely need to name the inputs whatever[] with emphatic emphasis on the []! This is what creates an array from the checkbox to appear in the $_POST/$_GET. Only those items selected will appear in the array. The value ought to be something useful (A value in the corresponding database table, say) which you can select for and query on...after sanitizing the input, of course.
So, your HTML input tag should look like this:
<input type="checkbox" name="process[]" value="<?php echo $employeeName ?>" >
You should have this coming back at you...
$_POST['process'][array(0=>name1, 1=>name2/*...etc*/)]
...which you can loop through with a foreach at your leisure.