Loop through an array of checkboxes and insert values - php

First time posting, hope all goes well :)
Been working on this for a while but basically I'm doing something like this: http://drupal.org/project/fancycheckboxes
I need to set a value of yes/no for each checkbox that I'm looping through and right now it works but is changing the value of all when I change one.
My foreach loop:
<?php $object = new stdClass(); $i = 0; ?>
<?php foreach( $filters as $key => $value ) {
?>
<tr>
<td><label for="show_filter">Show <?php echo $object->$key = $value['filter']; ?> Filter</label></td>
<td><input type="checkbox" class="show_filter" <?php //if ( $row['active_filter'] === 'yes' ) { ?>checked="checked"<?php //} ?> name="dp_show_filter" value="<?php echo $object->$key = $value['active_filter']; ?>"/><?php echo $object->$key = $value['active_filter']; ?></td>
<td><a class="button-primary" href="?page=profolio_theme&del=<?php echo $row['id'];?>">Delete</a></td>
</tr>
<?php
$i++;
}
and my jQuery:
jQuery(document).ready(function(e) {
var $ = jQuery.noConflict();
$i = 0;
customCheckbox = $('.dp_wrap input[type="checkbox"]');
showFilter = $('.dp_wrap input[name="dp_show_filter"]');
values = [];
return customCheckbox.each(function() {
// the element
var el = this;
// Hide checkbox
$(this).hide();
// Replace element
var rep = $('<span></span>').addClass('dp-checkbox').insertAfter(this);
// default state
if( $(showFilter).val() === 'yes'){
$(showFilter).prop('checked', true);
$(rep).removeClass('off').addClass('on');
} else {
$(showFilter).prop('checked', false);
$(rep).removeClass('on').addClass('off');
}
if($(this).is(':checked') ) {
$(rep).addClass('on');
} else {
$(rep).addClass('off');
}
// Click event
$(rep).click(function(e) {
e.preventDefault();
if( $(el).is(':checked') ) {
values.push($(showFilter).val('no'), ++$i);
$(el).prop('checked', false);
$(rep).removeClass('on').addClass('off');
} else {
values.push($(showFilter).val('yes'), ++$i);
$(el).prop('checked', true);
$(rep).removeClass('off').addClass('on');
}
});
});
});
Currenty my values are posting to a database as yes/no.
Any help is greatly appreciated and I hope my first post is an acceptable one.

It is changing all of the values as it looks as though you are giving the same name to every checkbox created on your page.
You can change your PHP code to something more like this:
<?php $object = new stdClass(); $i = 0; ?>
<?php foreach( $filters as $key => $value ) {
?>
<tr>
<td><label for="show_filter">Show <?php echo $object->$key = $value['filter']; ?> Filter</label></td>
<td><input type="checkbox" class="show_filter" <?php //if ( $row['active_filter'] === 'yes' ) { ?>checked="checked"<?php //} ?> name="dp_show_filter_<?php echo $row['id'] ?>" value="<?php echo $object->$key = $value['active_filter']; ?>"/><?php echo $object->$key = $value['active_filter']; ?></td>
<td><a class="button-primary" href="?page=profolio_theme&del=<?php echo $row['id'];?>">Delete</a></td>
</tr>
<?php
$i++;
}
Then change your default state to this and remove the if statement from underneath it:
// default state
if( $(this).val() === 'yes'){
$(this).prop('checked', true);
$(rep).removeClass('off').addClass('on');
} else {
$(this).prop('checked', false);
$(rep).removeClass('on').addClass('off');
}
I am pretty sure that will fix your problem as you described it. It is hard to tell without a more complete example of your code.

You iterate through your customCheckbox array with an each, but inside your loop, you access $(showFilter), which is a global array.
Did you mean $(showFilter[i]) ?
The each callback receives i (the index in the loop) as a parameter :
return customCheckbox.each(function(i) {
...
if( $(showFilter[i]).val() === 'yes'){ ...

Related

How to display checked checkbox from database in php?

I want to display checked checkbox which are stored as values in a mysql database.
For now the table stores the value of the checkbox being checked in the database. The header and first column are fetched from three different tables in the database. While the values of the checked check-boxes gets saved in a same table.
Here's the code for inserting the data.
$active = "CourseReport";
require_once 'pages/header.php';
require_once './functions/schema-functions.php';
require_once './functions/report-functions.php';
$course = Schema::getCourseReport();
$objective = Schema::getObjective();
$goals = Schema::getGoals();
$mainobj = Schema::getMainObjectives();
$subobj = Schema::getSubObjectives();
?>
<form id="addReport" action ='./functions/report-functions.php' method="post">
<table id="table1" class="table table-hover">
<thead>
<?php
echo '<tr><th>Goals</th>';
for ($i = 0; $i < count($course); $i++) {
echo '<th id = "rotate1">'. $course[$i]->commonName . '</th>';
}
echo '</tr>';
?>
</thead>
<tbody>
<?php
for ($y = 0; $y < count($goals); $y++) {
echo '<tr class="clickable"><th class="toggle">Goal#'.$goals[$y]['GoalId'].':'." " .' '.$goals[$y]['Goals'].'</th>
</tr>';
?>
<?php
for( $z = 0; $z < count($mainobj); $z++){
if($mainobj[$z]['GoalId'] == $goals[$y]['GoalId']) {
echo '<tr class="expander"><th class=row-header>Objective#'.$mainobj[$z]['MainObjId'].':'." ".' '.$mainobj[$z]['MainObjectives'].'</th>
</tr>';
?>
<?php
for ($j = 0; $j< count($subobj); $j++) {
if($mainobj[$z]['MainObjId'] == $subobj[$j]['MainObjId']){
echo '<tr class="expander"><td class=row-header>'.$subobj[$j]['SubObjId'].' ) '.$subobj[$j]['SubObjectives'].' </td>';
for ($x = 0; $x < count($course); $x++) {
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
}
echo '</tr>';
}
}
}
}
}
?>
</tbody>
</table>
<button class="button" name= "submit" value= "Submit">Submit</button>
</form>
report-functions.php
if( isset( $_POST['submit'], $_POST['check'] ) ){
try{
require_once 'db-connect.php';
$conn = DatabaseConnection::getConnection();
$sql= " insert into `Report` (`ColRow`) values (:value) ";
$stmt = $conn->prepare( $sql );
if( $stmt ){
$conn->beginTransaction();
foreach( $_POST['check'] as $index => $value ) {
$result = $stmt->execute( [ ':value' => $value ] );
if( !$result ) {
echo '
<script>
alert("Error, please try submitting again. Error code 1");
window.history.back();
</script>';
}
}
$conn->commit();
echo '<script>
alert("Report was submitted successfully.");
window.location = ".../";
</script>';
}
} catch( Exception $e ){
$conn->rollback();
exit( $e->getMessage() );
}
I expect that once I submit the table, the table should load the same table with the checked checkboxes. I should be able to make the changes and submit the table over and over again.
Please comment if I need to provide any additional information.
When you display your page (in your first section of code), at some point you do this:
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
The value is set to:
value=c"c.$course[$x]->courseId."-o".$subobj[$j]['SubObjId']";
This value is where you get the checked or not value you mentioned in the comments (like c1-o1.1).
Right. So before you do that echo, add a new if condition.
$value = "c$course[$x]->courseId" . "-o$subobj[$j]['SubObjId']";
if (verify_checked($value)) {
$checked_code = "checked=\"checked\"";
}
else {
$checked_code = "";
}
echo "<td><input name='check[]' type=checkbox value=$value id=checked $checked_code ></td>";
The verify_checked(value) function does (from what I understand of your database, you keep the "grid location" of checked elements):
function verify_checked($value)
{
// Connect to the database if needed
// Perform: SELECT count($value) FROM Report
// If the result is >0, return TRUE
// Else return FALSE
}
The idea here is to query the database every time your are about to echo the <input> element.
Note for concatenating text, I find it more legible to put spaces around the . to clearly split what is part of the text and what is the concatenation dot.
As mentioned previously, indentation is critical for understanding of the different contexts. Until I indented your code, I had not realized how the different loops worked in relation to the others.

Passing selected checkbox from array data into database with Codeigniter

i'm newbie for codeigniter. i trying to passing data attendance into database.
this my view code
<?php $no=1; foreach($employee AS $list_emp) { ?>
<tr>
<td><?= $no ?></td>
<td><input type="hidden" name="employee[]" value="<?php echo $list_emp->sn; ?>"><?= $list_emp->name; ?></td>
<td><?= $list_emp->position; ?></td>
<?php foreach ($attend_detail AS $list) {?>
<td><input type="checkbox" name="detail[]" value="<?php echo $list['details']"></td>
<?php } ?>
<td><input type="text" name="note[]"></td>
<input type="hidden" name="location[]" value="<?php echo $list_emp->branch; ?>">
</tr>
<?php $no++;} ?>
when i checked for 1 employee attendance (example 4630 is work), data can pass to database, but result like this (see image 2)
all data view input to database, not data when 1 checked before and remark WORK insert into row 1.
this my controller
function add_attend()
{
$employee = $this->input->post('employee');
$location = $this->input->post('location');
$detail = $this->input->post('detail');
$note = $this->input->post('note');
$total = count($employee);
if (empty($detail) === true) { $errors['detail'] = 'please select one';}
if (!empty($errors)){
$info['success'] = false;
$info['errors'] = $errors;
}
else {
for ($x=0; $x<$total; $x++){
$data = array(
'sn' => $employee[$x],
'lab' => $location[$x],
'stat' => $detail[$x],
'note' => $note[$x]
);
$this->m_human_capital->insert_attend($data);
}
$info['success'] = true;
}
$this->output->set_content_type('application/json')->set_output(json_encode($info));
}
and this my model
function insert_attend($data)
{
$this->db->insert('tb_attend_tes',$data);
}
i just want insert employee attendance who i checked. please help
thanks for anyone help.
sorry my bad english
Add an identifier on your employee attendance input name, so each employee have their own unique attendance dataset.
view :
...
<td><input type="checkbox" name="detail[<?php echo $no-1 ?>][]" value="<?php echo $list['details']"></td>
...
Since the attendance input is a multidimensional array, for the empty validation, you could use array_filter to check the whole attendance array.
And because of you are inserting an array data type into a single column, you need to concatenate it, you could use implode() function.
controller :
function add_attend()
{
$employee = $this->input->post('employee');
$location = $this->input->post('location');
$detail = $this->input->post('detail');
$note = $this->input->post('note');
$total = count($employee);
$filtered_detail = array_filter($detail);
if (empty($filtered_detail) === true) {
$errors['detail'] = 'please select one';
}
if (!empty($errors)){
$info['success'] = false;
$info['errors'] = $errors;
}
else {
for ($x=0; $x<$total; $x++){
$data = array(
'sn' => $employee[$x],
'lab' => $location[$x],
'stat' => (isset($detail[$x]) && !empty($detail[$x])) ? implode(",",$detail[$x]) : '',
'note' => $note[$x]
);
$this->m_human_capital->insert_attend($data);
}
$info['success'] = true;
}
$this->output->set_content_type('application/json')->set_output(json_encode($info));
}

Search filters not functioning on first attempt

I have a search filter based on flags of different colors.
If I will search based on color it is showing result but when I will select white color flag it is showing entire data in my database table. But If I choose any other color apart from white color for the first time it will show result. And if I choose white color flag second time,then it gives the correct result. What might be the reason. I need help
//filter on flag_color
if($this->input->get('flg')){
$arr_flag = explode('-', $this->input->get('flg'));
$str_flag = implode(',',$arr_flag);
if(6 == $str_flag){
$str_flag = 0;
}
$str_condition .= 'AND t.sender_flag_color_id IN('.$str_flag.')';
}
array(
'0'=>array(
'color'=>'White',
'path'=>'whiteflag.png'),
'1'=> array(
'color'=>'Blue',
'path'=>'blueflag.png'),
'2'=>array(
'color'=>'Green',
'path'=>'greenflag.png'),
'3'=>array(
'color'=>'Yellow',
'path'=>'yellowflag.png'),
'4'=>array(
'color'=>'Red',
'path'=>'redflag.png') ,
'5'=>array(
'color'=>'Orange',
'path'=>'orangeflag.png')
);
view
<?php
$arr_params = $this->uri->uri_to_assoc();
$arr_flag = array();
if(isset($arr_params['flg']))
{ ?>
<input type="hidden" id="flag_in_url" name="flag_in_url" value="yes" />
<?php
}
?>
<!-- id="webmenu1" -->
<select class="flag_color" onchange="urgency_select('flag_color')" name="header_flag" id="webmenuflag1">
<?php
$arr_params = $this->uri->uri_to_assoc();
$arr_flag = array();
$int_flag_url = '';
if(isset($arr_params['flg']))
{
$int_flag_url = $arr_params['flg'];
}
if(isset($arr_flag_color))
{
foreach($arr_flag_color as $key=>$flag_color)
{
if($int_flag_url == $key)
{
$flag_selected = 'selected';
}
else
{
$flag_selected = '';
}
?>
<option <?php echo $flag_selected;?> value="<?php echo $key;?>" data-image="<?php echo base_url();?>images/<?php echo $flag_color['path'];?>"></option>
<?php
}
}
?>
js: urgency_select
var flag_color_id = '';
if(select_option == 'flag_color' || $( "#flag_in_url" ).val() == 'yes')
{
if($( ".flag_color" ).val() != undefined)
{
var flag_color_id = $( ".flag_color" ).val();
if(flag_color_id == 0)
flag_color_id = 6;
search_url += 'flg/'+flag_color_id+'/';
}
}
Its because conflict with the value of white color flag...
In the view I changed the code
if($int_flag_url == $key)
{
$flag_selected = 'selected';
}
to
if($int_flag_url == 0 || $int_flag_url == $key)
{
$flag_selected = 'selected';
}

Passing information using post method without session variables

I will admit immediately that this is homework. I am only here as a last resort after I cannot find a suitable answer elsewhere. My assignment is having me pass information between posts without using a session variable or cookies in php. Essentially as the user continues to guess a hidden variable carries over all the past guesses up to that point. I am trying to build a string variable that holds them all and then assign it to the post variable but I cannot get anything to read off of the guessCounter variable i either get an undefined index error at the line of code that should be adding to my string variable or im just not getting anything passed over at all. here is my code any help would be greatly appreciated as I have been at this for awhile now.
<?php
if(isset($_POST['playerGuess'])) {
echo "<pre>"; print_r($_POST) ; echo "</pre>";
}
?>
<?php
$wordChoices = array("grape", "apple", "orange", "banana", "plum", "grapefruit");
$textToPlayer = "<font color = 'red'>It's time to play the guessing game!(1)</font>";
$theRightAnswer= array_rand($wordChoices, 1);
$passItOn = " ";
$_POST['guessCounter']=$passItOn;
$guessTestTracker = $_POST['guessCounter'];
$_POST['theAnswer'] = $theRightAnswer;
if(isset($_POST['playerGuess'])) {
$passItOn = $_POST['playerGuess'];
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$guessTestTracker = $_GET['guessCounter'];
$theRightAnswer = $_GET['theAnswer'];
}
else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['playerGuess'])) {
if(empty($_POST['playerGuess'])) {
$textToPlayer = "<font color = 'red'>Come on, enter something(2)</font>";
}
else if(in_array($_POST['playerGuess'],$wordChoices)==false) {
$textToPlayer = "<font color = 'red'>Hey, that's not even a valid guess. Try again (5)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if(in_array($_POST['playerGuess'],$wordChoices)&&$_POST['playerGuess']!=$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>Sorry ".$_POST['playerGuess']." is wrong. Try again(4)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if($_POST['playerGuess']==$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>You guessed ".$_POST['playerGuess']." and that's CORRECT!!!(3)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
}
}
}
$_POST['guessCounter'] = $passItOn;
$theRightAnswer=$_POST['theAnswer'];
for($i=0;$i<count($wordChoices);$i++){
if($i==$theRightAnswer) {
echo "<font color = 'green'>$wordChoices[$i]</font>";
}
else {
echo $wordChoices[$i];
}
if($i != count($wordChoices) - 1) {
echo " | ";
}
}
?>
<h1>Word Guess</h1>
Refresh this page
<h3>Guess the word I'm thinking</h3>
<form action ="<?php echo $_SERVER['PHP_SELF']; ?>" method = "post">
<input type = "text" name = "playerGuess" size = 20>
<input type = "hidden" name = "guessCounter" value = "<?php echo $guessTestTracker; ?>">
<input type = "hidden" name = "theAnswer" value = "<?php echo $theRightAnswer; ?>">
<input type = "submit" value="GUESS" name = "submitButton">
</form>
<?php
echo $textToPlayer;
echo $theRightAnswer;
echo $guessTestTracker;
?>
This is a minimal functional example of what you need to do. There are still a couple of minor bugs (like duplicate entries in the history), but I've left these as an exercise for you. Treat this as a starting point and build up what you need from it.
I've added comments to explain what's happening, so hopefully it is clear to you.
$answer = null;
$history = [];
$choices = ['apple', 'grape', 'banana'];
$message = '';
// check if a guess has been made.
if (!empty($_POST) && !empty($_POST['guess'])) {
// check if previous guesses have been made.
if (!empty($_POST['history'])) {
$history = explode(',', $_POST['history']);
}
// check guess.
if (!empty($_POST['answer']) && !empty($_POST['guess'])) {
// check guess and answer are both valid.
if (in_array($_POST['guess'], $choices) && isset($choices[$_POST['answer']])) {
if ($_POST['guess'] == $choices[$_POST['answer']]) {
// correct; clear history.
$history = [];
$message = 'correct!';
} else {
// incorrect; add to history and set previous answer to current.
$history[] = $_POST['guess'];
$answer = $_POST['answer'];
$message = 'incorrect!';
}
} else {
// invalid choice or answer value.
}
}
}
if (empty($answer)) {
// no answer set yet (new page load or correct guess); create new answer.
$answer = rand(0, count($choices) - 1);
}
?>
<p>Guess the word I'm thinking:</p>
<p><?php echo implode(' | ', $choices) ?></p>
<form method="POST">
<input type="hidden" name="answer" value="<?php echo $answer; ?>">
<input type="hidden" name="history" value="<?php echo implode(',', $history); ?>">
<input type="text" name="guess">
<input type="submit" name="submit" value="Guess">
</form>
<p><?php echo $message; ?></p>

codeigniter validating from textbox value(jquery) from array(php)

I want to validate whether my 3 input's are the same as the value in the array.
<?php
$aylength = 0;
$resultacyear = array();
foreach($academicyear->result() as $ay)
{
$item = array(
'tahunakademik' => $ay->Tahun_Akademik,
'idsemester' => $ay->ID_Semester,
'idlevelyear' => $ay->ID_Level_Year
);
$resultacyear[]= $item;
$aylength++;
}
?>
<script type="text/javascript">
$('#btn_save').click(function() {
<?php $inc = 0; ?>
for(i=0;i<parseInt(<?php echo $aylength?>);i++)
{
if($('#txt_tahunAkademik').val()=="<?php echo $resultacyear[$inc]['tahunakademik'] ?>" && $('#cb_semester').val()=="<?php echo $resultacyear[$inc]['idsemester'] ?>" && $('#cmb_YearLevel').val()=="<?php echo $resultacyear[$inc]['idlevelyear'] ?>")
{
alert ("Data already exists!!");
return false;
break;
}
else
{
<?php $inc++; ?>
return false;
}
}
});
</script>
When i tried, it didn't validate or even checks the value.
Is something wrong with my validation??

Categories