Inserting multiple checkbox values with a same text field value (codeigniter) - php

I'm trying to put values into a MySQL table like this one:
|---sbjct_name---|---level---|
|---------- Physics ----------|----Level 1-----|
|---------- Physics ----------|----Level 2-----|
|---------- Physics ----------|----Level 3-----|
|---------- Calculus ---------|----Level 1-----|
|---------- Calculus ---------|----Level 2-----|
(I don't know how to make table but I guess u get the idea)
Let say I'm going to put "Math" into sbjct_name column alongside with "Level 1", "Level 2", "Level 3" values into the level column.
The basic idea is from this pict (selecting value for a same input text value).
Instead of inserting "Math" multiple times for each level,
I'm trying to make it one time submit with checkbox tag. It will be something like this pict (with checkbox).
I don't have any idea how to make this happen (or if it possible in CI).
This is some code from my Controller,
public function add_subject()
{
$data = array();
if ($this->input->post('savebttn'))
{
$this->form_validation->set_rules('sbjct_name', 'Subject Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('level', 'Level', '|required|is_natural');
$this->form_validation->set_error_delimiters('<span class="fielderror">','</span>');
if ($this->form_validation->run() == FALSE)
{
$data['reset'] = FALSE;
}
else
{
//I don't know what to do here
//I don't know what to do here
//I don't know what to do here
//I don't know what to do here
}
}
$data['level'] = $this->admin_model->get_checkbox_option('level', 'lvl_id', 'lvl_name');
$data['page'] = 'createsubject';
$this->load->view('admin/main', $data);
}
This is a checkbox view function in the Model,
public function get_checkbox_option($table, $id, $name, $selected=0)
{
$query = $this->db->get($table);
$select= '';
if ($query->num_rows() > 0)
{
foreach ($query->result_array() as $row)
{
$selected_option = ($selected == $row[$id]) ? 'selected = "selected" ':' ';
$select .='<input type="checkbox" name="level" value="'.$row[$id].'" '.$selected_option.'>'.$row[$name].'<br>';
}
}
return $select;
}
This is the form on the View,
<form action="" method="post" id="createcategoryform">
<table>
<tbody>
<tr>
<td><div class="label">Subject Name</div></td>
<td><div class="input">
<input type="text" name="sbjct_name" size="39" class="ui-corner-all input-text validate[required]">
<?=form_error('sbjct_name');?>
</div></td>
</tr>
<tr>
<td><div class="label">Level</div></td>
<td><div class="input-text ui-corner-all validate[required]">
<?=(isset($level)) ? $level: '';?>
</div><?=form_error('level');?></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Save" name="savebttn" class="input-button ui-corner-all ui-state-default"></td>
</tr>
</tbody>
</table>
</form>
I will be grateful if you can give any clue. :D

first
make your checkbox as an array so it look like this
$select .='<input type="checkbox" name="level[]" value="'.$row[$id].'" '.$selected_option.'>'.$row[$name].'<br>';
give attention to the name. yours name="level" and mine name="level[]"
, then you can grab all level as one variable
second
make your controller like this
if ($this->form_validation->run() == FALSE)
{
$data['reset'] = FALSE;
}
else
{
// make array container for input batch
$insertData = array();
if(!empty($this->input->post('level'))) {
foreach($this->input->post('level') as $level) {
$tempArray = array(
'sbjct_name' => $this->input->post('sbjct_name'),
'level' => $level
);
array_push($insertData, $tempArray);
}
// it's better to put this in model
// but for example purpose I put it there
$this->db->insert_batch('table', $insertData);
//do what you want to do here
}
}
hope you get the point #nasamikhail

Related

Conditional select from a table using codeigniter

Im trying to make a select which only shows some information (a conditional select).
I mean, this is my table "usuarios":
"usuarios" includes:(id,username,name,lastname,password,type,status,date)
Take a look:
My goal is to make a select that only shows the users with "type" = 1 AND "status" = 1
Take a look:
I have a done a select but it shows every usernames, it does not validates anything :/.
My program shows this, and it is not correct because it does not validate anything :/
Here is my code:
My controller file:
public function edit($ID){
$data['usuarios'] = $this->Crudmodel->get_usuarios();
$data['record']=$this->Crudmodel->get_id_row($ID);
$this->load->view('edit',$data);
}
My model file:
public function get_usuarios() {
$this->db->select('c.*')
->from('usuarios c');
$q = $this->db->get();
return $q->result();
}
My "edit" file:
<h2 align="center">UPDATE</h2>
<form method="post" action='<?php echo site_url('Home/saveupdate'); ?>'>
<tr>
<td><input type="text" hidden name="txtid" value="<?php echo $record->id ?>"/></td>
</tr>
<tr>
<td>
<select name="txtcarr">
<?php foreach($usuarios as $item):?>
<option value="<?php echo $item->id;?>"><?php echo $item->username;?></option>
<?php endforeach;?>
</select>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Save"/></td>
</tr>
Dont know whatto do :/
Why not only select the rows you want? Will it work as you expect if you put this in your model?
public function get_usuarios() {
$this->db->select('id, username')
->from('usuarios')
->where(array('status'=>1, 'type'=>1));
$q = $this->db->get();
return $q->result();
}

Select columns from mysql table by given array in php(CodeIgniter).

I want to select columns form mysql table which I have selected names as input value. In my view, have to select column names as multiple input fields. In this selection option values are equals to column names in my “pass_due” table in database.
<form id="" name=" Passdue " action="<?=base_url('index.php/Passdue_ctrl/select')?>" method="post">
<div >
<input class="date-picker" id="report_date" name="report_date" value="" placeholder="Select Date"/>
<select multiple="" class="chzn-select" id=" " data-placeholder="Select sections " name="table_feilds">
<option value="" />
<option value="below_1" /> Below month
<option value="month_1_3" /> Month 1-3
<option value="month_3_6" /> Month 3-6
<option value="month_6_9" /> Month 6-9
<option value="over_9" /> Over 9 month
</select>
</div>
<div>
<button type="submit" class="btn btn-mini btn-info">Submit</button>
<button type="reset" id="reset" class="btn btn-mini btn-info">Reset</button>
</div>
</form>
This is function in my controller
Function select (){
$fld_name =$this->input->post('table_feilds');
$reportdate=$this->input->post('report_date');
$report=$this->Passdue_model->get_report_part($fld_name,$reportdate);
If($report){
$this->data['report_part']=$report;
$this->data['fld_name']=$fld_name;
$this->load->view('Passdue_other_view',$this->data);
}
}
In my model like this.
function get_report_part1($fld_name,$reportdate)
{
$this->db->select($fld_name);
$this->db->from(‘pass_due’);
$this->db->where('fld_actORinact_date <=',$reportdate);
$query = $this->db->get();
if($query){
return $query->result();
}
}
When I run this code it select all columns from table, not only selected ones. And also it shows error as
Invalid argument supplied for foreach() .
You can use this new model method to retreive data from your db.So insert this method into your model
function getDetail($tablename = '', $columns_arr = array(), $where_arr = array(), $limit = 0, $offset = 0)
{
$limit = ($limit == 0) ? Null : $limit;
if (!empty($columns_arr)) {
$this->db->select(implode(',', $columns_arr), FALSE);
}
if ($tablename == '') {
return array();
} else {
$this->db->from($tablename);
if (!empty($where_arr)) {
$this->db->where($where_arr);
}
if ($limit > 0 AND $offset > 0) {
$this->db->limit($limit, $offset);
} elseif ($limit > 0 AND $offset == 0) {
$this->db->limit($limit);
}
$query = $this->db->get();
return $query->result();
}
}
//These are include within controller methods
$fld_name =$this->input->post('table_feilds');
//you have to send your columns from your multiple select object as array.
//create column array
$arr_columns=array();
for($i=0,$i<=count($fld_name);$i++){
$arr_columns=array_push($fld_name)
}
$reportdate=$this->input->post('report_date');
//create where array
$arr_where=array('fld_actORinact_date <=' => $reportdate);
//retreive data
$datatable=‘pass_due’;
$report=$this->Passdue_model->getDetail($datatable,$arr_columns,$arr_where,0,0);
var_dump($report);
//finally dump_data set .it return array object.Then loop retrieved object.
then this will return what you expect.
Also like to advise you to use generalized model except using separate models for each & every tables.
use below code in form
<select multiple="multiple" class="chzn-select" id=" " data-placeholder="Select sections " name="table_feilds[]"> <!-- use [] for multiple values -->
and I don't see any foreach loop?
and first
echo '<pre>';print_r($fld_name);exit; before
$report=$this->Passdue_model->get_report_part($fld_name,$reportdate);
In your model return the query as follows
return $query->result_array();
In your controller get data by
data['fld_name']=$this->Passdue_model->get_report_part($fld_name,$reportdate);
$this->load->view('Passdue_other_view',$data);
In your view page
foreach($fld_name as $fld_name){?> <th><?php echo $fld_name['column_name '];?></th> <?php }?> </tr> </thead>

Retrieve POST checkbox data from form if they exist

Hello knowledgeable people. I am having trouble retrieving checkbox data from form. I have a site in which user can add checkboxes themselves, so I am writing them out like this:
<table style="padding:10px;">
<?php
$query_boolean = $DB->prepare("SELECT * FROM moduls WHERE type='boolean'") or die(mysql_error());
$query_boolean->execute();
while (($row = $query_boolean->fetch()) != false)
{
?>
<tr>
<td>
<?php echo $row->name ?>:
</td>
<td>
<?php
$s = "";
$s .= sprintf('<input type="checkbox" class="textbox" name="boolean_%s" value="yes">%s', $row->id, Yes);
$s .= sprintf('<input type="checkbox" class="textbox" name="boolean_%s" value="no">%s', $row->id, No);
echo $s;
?>
</td>
</tr>
<?php
}
?>
</table>
Now I have an advanced search in which I have to chech through every checkbox to see what has been selected (ether none, Yes, No, or both). How can I get the info from every checkbox in variables? Thank you so much!
To get POST data from checkboxes they must have attribute
checked="checked"
EDIT:
If you have 2 checkbox as this..
<input type="checkbox" checked="checked" class="textbox" name="boolean_yes" value="yes">
<input type="checkbox" class="textbox" name="boolean_no" value="no">
When you submit your form the checkbox with attribute checked will be sent as POST and the one without checked attribute will not be sent..
if(isset($_POST['search'])) {
$all_checked = array();
foreach($_POST as $key=>$value){
if(strpos($key, "boolean_") > -1){
$all_checked[$key] = $value;
}
}
var_dump($all_checked);
}
This way you will get inside $all_checked array all marked boxes.. All others checboxes are not marked!
if you want to get checkbox value then use checkbox name as array
<input type="checkbox" name="email1[]" value="">
an get it on another page by
<?php
$var2 = $_POST['email1'];
$v=implode(",",$var2);
echo $v;
?>
try it

Yes/no variable radio option

I am trying to make a variable yes/no radio type.
My script is:
while ($row1 = mysql_fetch_assoc($vragen))
{
$type = $row1['type'];
if ($type == 'kort')
{
echo '
<tr>
<td width="60%">'
.$row1['vraag'].'
<input type="hidden" name="vragen'.$aantalBranches.'[]" value="'.$row1['vraag'].'"/>
</td>
<td>
<input type="text" name="antwoorden'.$aantalBranches.'[]"/>
</td>
</tr>';
}
elseif ($type == 'lang')
{
echo '
<tr>
<td width="60%">'
.$row1['vraag'].'
<input type="hidden" name="vragen'.$aantalBranches.'[]" value="'.$row1['vraag'].'"/>
</td>
<td><textarea name="antwoorden'.$aantalBranches.'[]" cols="30"rows="5"></textarea><td/>
</tr>';
}
elseif ($type == 'ja,nee')
{
echo'
<tr>
<td width="60%">'
.$row1['vraag'].'
</td>
<td>
<input type="radio" name="optie'.$c.'" value="yes">Yes
<input type="radio" name="optie'.$c.'" value="no">No
</td>';
if ('optie'.$c.'' == 'yes')
{
echo'
<td><input type="hidden" name="vragen'.$aantalBranches.'[]" value="'.$row1['vraag'].'"/></td>
<td><input type="text" name="antwoorden'.$aantalBranches.'[]" value="yes"/></td>
</tr>';
}
else
{
echo'
<td><input type="hidden" name="vragen'.$aantalBranches.'[]" value="'.$row1['vraag'].'"/></td>
<td><input type="text" name="antwoorden'.$aantalBranches.'[]" value="no"/></td>
</tr>';
}
$c++;
}
}
echo '</table>';
$aantalBranches++;
}
The problem is that i want the result stored in 1 variable the $antwoorden [] so the most logic way was a if else for this but for a strange reason it doesn't work any1 can help me ?
It now only shows "no" even if i change it to "yes".
I edited the script and added the other choises of the form long and short fields(textarea/inputfield)
Thanks in advance.
if ('optie'.$c.'' == 'yes')
This part will always evaluate to false.
You probably don't know how this variable is going to be named because name depends on value from variable $c and this is what is giving you difficulties.
To overcome this you could just pull all of the variables that start with 'optie' string and then cycle through them when you want to use them. You can also access this variable like this.
$optionname = 'optie'.$c;
$optionvalue = $$optionname;
// or
$optionvalue = $_POST[$optionname];
But generally speaking looking at your code it is very badly structured and I would consider restructuring that code. But without more context I can't give you more instructions on how to do this.
Update:
Just change mentioned condition to:
if ($_POST['optie'.$c] === 'yes')
Or change $_POST to $_GET if you are using 'GET' http request to pass 'optie' variables.
It always shows no because this can never evalulate to true:
if ('optie'.$c.'' == 'yes')
A string that contains optie will never match yes. So the else block is always entered that outputs the no value.

Retrieve data from mysql and update them accordingly

I want to retrieve data from my MySQL database and display it as a table (I don't mind any style, but preferred as a table). Then the data should display with a radio button or a normal button which update that specific row and changing a single column in that row to Active (Status making Active).
I have started it, but I still have issues with adding a radio button or a button. Then I thought of displaying the information in a table which inside a form. This form will have each radio buttons, when the person select that radio button and press submit. The data should be updated in the MySQL database.
Can someone guide me about this? I'm a bit confused. I'm confused because I have to add a form and in that form I have to add a table and all this stuff should be in a php file.
on formpost.php page you can do something like this for handling the list array you received from the previous page:
<?
$list = $_POST['list'];
foreach ($list as $key => $list_php)
{
$query1 = "SELECT * FROM `stu_entry` WHERE `stu_entry`.`Student_No` = '$list_php' AND `stu_entry`.`Out_Time` = '0000-00-00 00:00:00'";
$result1 = mysql_query($query1);
$row1=mysql_fetch_array($result1);
//whatever you want to do
}
?>
I forgot to tell you something in the previous post. In the form page, lets say you have 100 rows with 100 checkboxes. It would be nasty to manually check or uncheck all of them. As an alternative you could append a little script at the end of the page to handle the checking/ unchecking process for you:
<script>
function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}
function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}
function countChecks(form){
var t=0;
var c=form['list[]'];
for(var i=0;i<c.length;i++){
c[i].checked?t++:null;
}
return t;
}
</script>
<input type="button" name="CheckAll" value="Check All"
onClick="checkAll(document.formpost['list[]'])">
<input type="button" name="UnCheckAll" value="Uncheck All"
onClick="uncheckAll(document.formpost['list[]'])">
<i>with selected: </i>
<select name="submit_mult" id="submit_mult">
<option value="todo1">Action 1 </option>
<option value="todo2">Action 2 </option>
</select>
<input type="button" name="go" value="Go" onClick='if(countChecks(this.form)>0) {if(confirm("are you sure you want to \""+document.getElementById("submit_mult").options[document.getElementById("submit_mult").selectedIndex].text+" "+countChecks(this.form)+" items selected"+"\"")) {document.getElementById("referenceToSomeHiddenElement").value=document.getElementById("submit_mult").options[document.getElementById("submit_mult").selectedIndex].value;document.getElementById("formpost").submit();}} else alert("you have not selected any item!!")' >
Tell me if you need more help on this.
I first specify a MySQL command which in return gives me an array. I use a while statement to do something to each item in the array. The array is populated with the field name and the field contents.
$mysql = mysql_query("SELECT * FROM table");
while ($array = mysql_fetch_array($mysql))
{
$output .= '<form>Row: ' . $array['fieldname'] . ' <input type="button" value="Update" /></form>';
}
This extracts all rows from the table and adds a form to the variable $output for every result. I'm unsure of how you want to update your database, so you will have to look into it. You can use GET and POST methods.
Go ahead and try something like this. And tell me if that worked:
<p><b>your page name</b></p>
<form name="formpost" id="formpost" action="formpost.php" method="POST">
<table border="2" cellpadding="5" cellspacing="1" style="border-collapse: collapse" bordercolor="#999999" width="800">
<tr>
<td><b>Sno.</b></td>
<td><b>Field name1</b></td>
<td><b>Field name2</b></td>
<td><b>Field name3</b></td>
<td><b>Field name4</b></td>
<td><b>Field name5</b></td>
<td><b>Field name6</b></td>
<td><b>Field name7</b></td>
</tr>
<?
$sorting="";
if($orderby!="" && $direction!="") $sorting=" ORDER BY $orderby $direction";
$query = "SELECT * FROM table WHERE something = 'something' $sorting";
$result = mysql_query($query);
?>
<tr>
<?
$i=0;
while ($row = mysql_fetch_array($result))
{
$i++;
?>
<td><input type="checkbox" name="list[<?echo $i?>]" id="list[]" value="<?echo $row['some_primary_field_id']?>"><?echo $i?></td>
<td><?echo $row['Field1']?></td>
<td><?echo $row['Field2']?></td>
<td><?echo $row['Field3']?></td>
<td><?echo $row['Field4']?></td>
<td><?echo $row['Field5']?></td>
<td><?echo $row['Field6']?></td>
<td><p align="center">
<?
echo "<input title='button' name='change this row' value='Some Button' type='button' onClick=\"if(confirm('Press OK to change status to confirm')) {document.getElementById('someid').value='".$row['Field1']."';document.getElementById('formpost').submit();}\"/>";
?>
</td>
</tr>
<input type='hidden' name="hiddenlist[<?echo $i?>]" id="hiddenlist[]" value="<?echo "some boundry condition ".$row['Field2']?>">
<?
} //end of while
?>
</table>
</form>

Categories