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>";
}
Related
I am pretty stumped, I thought this would work for sure. I want to insert multiple checkbox values (if selected) into different columns of one table. I was attempting to do this with a for loop and keeping the naming convention consistent so I could utilize the for loop with the checkbox array. Here is php code:
$connection = new mysqli("localhost","root","","employee_db");
if(isset($_POST['check'])){
$check = $_POST['check'];
if($check){
print_r($check);
}else{
echo "nothing checked";
}
for($i=0;$i<sizeof($check);$i++){
$query = "INSERT INTO `checklist_test` (`$check[$i]`) VALUE (`\"$check[$i]\"`)";
$result = mysqli_query($connection,$query);
if(!$result){
die("NOPE <br>" . mysqli_error($connection));
}else{
echo "yup";
}
}
}
And here is the HTML
<form action="" method="post>
<input type="checkbox" name="check[]" value="check1">Check1
<input type="checkbox" name="check[]" value="check2">Check2
<input type="checkbox" name="check[]" value="check3">Check3
<input type="submit" value="submit">
</form>
The MySQL Columns are "id, check1, check2, check3" so SQL should look like:
INSERT INTO `checklist_test` (`id`, `check1`, `check2`, `check3`)
VALUES (NULL, 'test', 'test', 'test');
Appreciater outside P.O.V. that I need thanks!
If you the execute the query inside the loop, you would be executing x number of queries (or inserting x number of rows) rather than inserting into x number of columns. There is really no need to use a loop here since you have a set number of columns.
Use echo statements to print out the queries to see what you are running and you'll see why this isn't working.
You also should never put user input directly into a MySQL query. Read up on SQL injections.
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.
This is probably an easy one but I am stuck. I have a form with checkboxes that show employees and there skills, these are taken from a table with a many to many relationship.
The below code works for updating the records but I am unsure on how to delete records if the checkbox is un-checked
$emp=$_POST['emp'];
if(isset($_POST['chk1'])){
$checkbox=$_POST['chk1'];
$arr_num=count($checkbox);
$i=0;
while ($i < $arr_num)
{
$qry = "INSERT IGNORE INTO skillsets (skill_id, empr_id )VALUES(?, ?)";
$stmt = $mysqli->prepare($qry);
$stmt->bind_param('ii', $checkbox[$i], $emp);
$stmt->execute();
$i++;
}
}
else .... delete from .....
I am not sure of the syntax for the else, can someone help me out?
You can define hidden inputs for every checkbox (before it) with the same name. Eg.
<input type="hidden" name="items[1]" value="no" />
<input type="checkbox" name="items[1]" value="yes" />
1 is your item ID.
And now if checkbox is checked then its value will be send. In other case, value from hidden field will be send to your server. With this data you can iterate through items array, get ID from index and check value to know if it's checked or not.
Thanks for taking the time to look at this question.
Currently, I have a piece of code that creates four checkboxes labeled as "Luxury, Brand, Retailer," and "B2B." I have looked into a number of PHP methods to create checkboxes, and I felt the implode() function was the most simple and suitable for my job. I have looked into a number of tutorials to create the implosions, however, they did not fit my criteria, as I would like the database values be reflected in the front-end. Currently in my database, the implode() works, therefore (for example), if I check "Luxury", "Brand", "Retailer", and press the "Submit" button, the three items "Luxury, Brand, Retailer" will be in that specified cell. It looks like my code works in the back-end, but these are my issues:
I am not exactly sure (despite multiple Googles) how to retrieve those values stored in the single-cell array, and have it selected as "selected" (this would "check" the box in the front-end)
Could someone kindly take a look at my code below and let me know what seems to be missing/wrong/erroneous so I could attempt the revisions? Anything would be appreciated, thank you!
<?
if (isset($_POST['formSubmit2'])){
$category = mysql_real_escape_string(implode(',',$_POST['category']));
$accountID = $_POST['accountID'];
mysql_query("UPDATE Spreadsheet SET category='$category' WHERE accountID='$accountID'");
}
$query = mysql_query("SELECT * FROM Spreadsheet LIMIT $firstRow,$rpp");
while($row = mysql_fetch_array($query)){
// Begin Checkboxes
$values = array('Luxury','Brand','Retailer','B2B');
?>
<form name ="category" method ="POST" action ="" >
<?
echo "<input type = 'hidden' name = 'accountID' value = '" . $row['accountID'] . "' >";
for($i = 0; $i < count($values); $i++){
?>
<input type="checkbox" name="category[]" value="<?php echo $values[$i]; ?>" id="rbl_<? echo $i; ?>" <? if($row['category'] == $i) echo "checked=\"checked\""; ?>/>
<? echo $values[$i] ?><br>
<? } ?>
<input type ="Submit" name ="formSubmit2" value ="Submit" />
</form>
<? } ?>
The best approach i can recommend given what you have is to, explode the values out of the db giving you a new array of all the select fields. Then use in_array to compare the list you have with this new list in the loop. then flag the checkboxs as needed.
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.