Display value in view - codeigniter

In this codeigniter model i have this query testing if value entered in input exists in database..
function get_search_form() {
$match = $this->input->post('search1');
$this->db->where('numero',$match);
$this->db->where('inscris','non');
$q = $this->db->get('transaction');
if($q->num_rows()>0)
{
foreach($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
Behold the controller i'd like to display value grabbed in input in view inscription.php
function search()
{
$data['row'] = $this->site_model->get_search_form();
$this->load->view('acceuil/aside');
$this->load->view('acceuil/inscription', $data);
}
My issue is how to display in that view input value and a form if this value exists in database ?
I have tried like this but i need help :
inscription view:
<?=form_open('navigation/search');?>
<input type="text" name="search1" id="search1" required />
<input type='submit' value='Display' />
<?=form_close();?>
I try to display the form like this but i don't know how to display as well the input value entered
<?php
if( $row > 0 )
{
?>
les champs du formulaire ici....
<?php
}else
{ }
?>

In your view you can check if the variable $row is not null (because it will be null when no rows are found):
if ($row !== null) {
// do stuff
}
You can modify the model function to return some other value if no rows are found, for example, by setting the $data to an empty array:
function get_search_form() {
$match = $this->input->post('search1');
$this->db->where('numero',$match);
$this->db->where('inscris','non');
$q = $this->db->get('transaction');
$data = array(); // <--- here
if($q->num_rows()>0)
{
foreach($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
And then in the view you can simply loop the data:
foreach($row as $r) {
// do stuff
}
or you can implode the array to use as the input value:
<input type="text"
name="search1"
id="search1" required
value="<?php echo implode(' ', $row); ?>" />
You could also use html entities here, in case double quotes are possible to appear in what your model function returns (I have no idea what it returns).

you can access $data global object like this check
<?php
if( isset($row))
{
foreach($row as $v){
//Do the operations here
}
}else
{
//Do the operations here
}
?>

Related

undefined variable in codeigniter view which is already defined in the controller

This is my controller. here i declared current_company.
public function index($id='')
{
$this->load->model('Company_model');
($id!='') ? $data["company_details"]=$this->Company_model->get_company($id) :'';
($id!='') ? $data ["current_company"]=$this->Company_model->get_currentcomp($id) :'';
$this->load->view('includes/header');
$this->load->view('includes/left_menu');
$this->load->view('company/manage',($id!='') ? $data : '');
$this->load->view('includes/footer');
}
This is my model. Here i declared the function
class Company_model extends CI_Model{
protected $strTableName = 'suc_company';
function __construct(){
parent::__construct ();
$this->db->from($this->strTableName);
}
function get_currentcomp($intPkId){
$this->db->where('pk_bint_company_id',$intPkId);
$q1 = $this->db->get($this->strTableName);
return $q1->result_array()[0];
}
This is the view part. here i called the $current_company !== FALSE then
<div class="form-group">
<label for="company_package" class="col-sm-3 control-label"> Package</label>
<div class="col-sm-9 col-xs-12">
<?php if ($current_company !== FALSE ) {?>
<select name="company_package" class="form-control select2" disabled="">
<option value="<?php echo $company_package;?>" selected=""><?php echo $packagename;?></option>
</select>
<?php } else { ?>
<?php } ?>
Error
an error is occurring... undefined data current_company
Change your controller code like this.
public function index($id='')
{
$this->load->model('Company_model');
$data["company_details"] = false;
$data["current_company"] = false;
if($id != ''){
$data["company_details"] = $this->Company_model->get_company($id);
$data["current_company"] = $this->Company_model->get_currentcomp($id);
}
$this->load->view('includes/header');
$this->load->view('includes/left_menu');
$this->load->view('company/manage',$data);
$this->load->view('includes/footer');
}
As said in comment, you are leaving possibility that maybe $data wouldn't be passed to view file. You have to restrict this kind of oscillations.
Try this way:
public function index($id='')
{
if ((int)$id < 1) {
redirect('some/generic/place', 'refresh');
}
// we have integer in parameter
// so we will check if data by that parameter exists
$data = [];// initialization of array so we are sure $data is set
$this->load->model('Company_model');
$data['company_details'] = $this->Company_model->get_company($id);
if ($data['company_details']) {
$data['current_company'] = $this->Company_model->get_currentcomp($id) :'';
} else {
// in this point $data is an empty array
}
// $this way variable will be available in all view files
$this->load->var($data);
$this->load->view('includes/header');
$this->load->view('includes/left_menu');
$this->load->view('company/manage');
$this->load->view('includes/footer');
// so now, in your view you would have wether company with details wether an empty array
// *first line of code assumes parameter would be an integer
// **also assumed that $this->Company_model->get_company($id) would return false/null/anEmptyArray if data doesn't exist
}

Codeigniter db->where() not working in foreach loop

On my view I need to be able to get the hidden banner_image_id and use that in my $this->db->where('banner_image_id', $id) on my model function
When I update the image. It does not update to the correct row. Instead it update all rows with the same filename.
Question: On my model how can I make sure that my $this->db->where('banner_image_id', $id) updates correct rows.
I have done a vardump($id) and result is string(2) "63" which is correct but still updates every row the same. I tried update_batch also no luck.
Model Function
public function edit_banner_image($file_name) {
$banner_image_id = $this->input->post('banner_image_id');
if (isset($banner_image_id)) {
foreach ($banner_image_id as $id) {
//var_dump($id);
//exit;
$data = array('banner_id' => $this->uri->segment(4),'banner_image' => $file_name);
$this->db->where('banner_image_id', $id);
//$this->db->where_in('banner_image_id', $id); // Tried No Luck
//$this->db->or_where_in('banner_image_id', $id); // Tried No Luck
$this->db->update($this->db->dbprefix . 'banner_img', $data);
}
}
}
View Table
<table>
<tbody>
<?php foreach ($banner_images as $img) { ?>
<tr>
<td>
<?php echo $img['banner_image_id'];?>
<input type="hidden" name="banner_image_id[]" value="<?php echo $img['banner_image_id'];?>">
</td>
<td>
<input type="file" name="banner_image[]" multiple size="20">
</td>
<td>
<img src="<?php echo base_url() . 'uploads/' . $img['banner_image'];?>" />
<input type="hidden" name="banner_image" value="<?php echo $img['banner_image'];?>">
</td>
</tr>
<?php }?>
<tbody>
</table>
Try to concatenate the id numbers in foreach loop and pass it where function at once.
Assuming that your id numbers are array(1,2,5,6).
public function edit_banner_image($file_name) {
$banner_image_id = $this->input->post('banner_image_id');
if (isset($banner_image_id)) {
$bid = 'IN(';
foreach ($banner_image_id as $id) {
$bid .= $id . ',';
}
$bid = substr($bid, 0, -1) . ')'; //remove last comma and add closing paranthesis.
//The content of the variable $bid would be like
//IN(1,2,5,6)
$data = array('banner_id' => $this->uri->segment(4),'banner_image' => $file_name);
$this->db->where('banner_image_id', $id);
$this->db->update($this->db->dbprefix . 'banner_img', $data);
}
}
Another Suggestion:
Convert $banner_image_id to a normal array in case of it is an associative array.
public function edit_banner_image($file_name) {
$banner_image_id = $this->input->post('banner_image_id');
$bid = array();
if (isset($banner_image_id)) {
foreach ($banner_image_id as $id) {
$bid[] = $id;
}
$data = array('banner_id' => $this->uri->segment(4),
'banner_image' => $file_name);
$this->db->where_in('banner_image_id', $bid);
$this->db->update($this->db->dbprefix . 'banner_img', $data);
}
}
I suggest you to make convertion in the controller section, not in model. The lines ending with // should be in the controller. You can easily pass $bid to edit_banner_image($file_name, $bid) function then.
public function edit_banner_image($file_name, $bid) {
$banner_image_id = $this->input->post('banner_image_id'); //
$bid = array();//
if (isset($banner_image_id)) {//
foreach ($banner_image_id as $id) { //
$bid[] = $id;//
}
$data = array('banner_id' => $this->uri->segment(4),
'banner_image' => $file_name);
$this->db->where_in('banner_image_id', $bid);
$this->db->update($this->db->dbprefix . 'banner_img', $data);
}
}
Thus, you will have more readable code.

redirect issue in codeigniter when using if statement

i have been trying to redirect the same previous page after delete or inserting the data using if condition in the controller to flash the message but there is something i am missing.
<form action="<?php echo base_url(); ?>curdler/add/tbl_category/addCat/category" method="post">
Category Title<input type="text" name="category_title"/> </br>
<input type ="submit" value="submit">
</form>
<?php echo $this->session->flashdata('msg'); ?>
Controller
public function add() {
$data = $_POST;
$tableName = $this->uri->segment(3);
$content = $this->uri->segment(4);
$folderName = $this->uri->segment(5);
$this->load->model('curdmodel');
if($this->curdmodel->add($data, $tableName)){
$this->session->set_flashdata('msg', 'Category added');
redirect('welcome/index/'.$content.'/'.$folderName);
} else{
$this->session->set_flashdata('msg', 'Category Not Added');
}
}
when using the if statement it goes to the different url but without if statement its working fine.
model
public function add($data, $tableName) {
$this->db->insert($tableName, $data);
}
Your redirect only occurs if the if statement evaluates to be true, if the condition is false codeigniter is just setting the flashdata and then ending the script.
Consider changing the order of your code to something like
if($this->curdmodel->add($data, $tableName)){
$this->session->set_flashdata('msg', 'Category added');
} else{
$this->session->set_flashdata('msg', 'Category Not Added');
}
redirect('welcome/index/'.$content.'/'.$folderName);
Additionally, your model does not contain any return value and therefore will never pass data back for the if statement to be evaluated. You should update your model as follows:
public function add($data, $tableName) {
$this->db->insert($tableName, $data);
if($this->db->affected_rows() > 0) {
return true;
}
}

Codeigniter. Controller cannot receive session data

I set session successfully as output profiler show me session name and value.
But when I POST data controller cannot receive session data.
Library is loaded, $config['sess_expire_on_close'] = TRUE I've changed TRUE-FALSE without any success. Also tried rewrite code.
And another question I use two PC and on Linux machine I get error "Header already sent...", but on Win machine I don't receive this message. How to enable it on Win PC. Notices and warnings are enabled.
So ...
Controller kmgld:
function authorisation_user()
{
......
$data['set_cookie'] = "Surname";
......
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->output->enable_profiler(TRUE); //show me only session name and value which I set
}
View:
if ($set_cookie!=NULL)
{
$this->session->set_userdata('surname',$set_cookie);
}
<!Doctype...>
<form action="<?php echo base_url()?>index.php/kmgld/update_kmgld" method="post" name="">
And again Controller kmgld
function update_kmgld()
{
...update DB
$test=$this->session->userdata('surname');
echo $test; //it is NULL
$this->output->enable_profiler(TRUE); // show me only now session id, ip, user agent
}
you have to set the userdata in the controller, the view isn't the proper place for it. so you probably would do something like this in your controller:
$surname = "Surname";
$this->session->set_userdata('surname',$surname);
$data['set_cookie'] = $surname;
...
$this->load->view('vheader', $data);
don't know if you autoload the session library. otherwise you have to load it in every function you need it.
remove session setting from view and do it in controller:
function authorisation_user()
{
$data['set_cookie'] = "Surname";
$this->session->set_userdata('surname',$set_cookie);
$this->load->view('vheader', $data);//are you sure here is where $data should go ?
$this->load->view('vuser_kmgld');//not $data here?
$this->output->enable_profiler(TRUE); //show me only session name and value which I set
}
Controller:
<?php
class Kmgld extends CI_Controller {
function index()
{
$data['flag'] = "first";
$this->load->model('Mkmgld');
$this->load->view('vheader');
$this->load->view('vauthorisation',$data);
$this->load->view('vfooter');
}
function get_kmgld()
{
$this->load->model('Mkmgld');
$this->Mkmgld->get_kmgld();
$this->load->view('vheader');
$this->load->view('kmgld');
$this->load->view('vfooter');
}
function authorisation_user()
{
$this->load->model('Mkmgld');
$surname_session = $this->session->userdata('surname');
$data['surname_post'] = mb_convert_case($this->input->post('surname'), MB_CASE_TITLE, "UTF-8");
$data['user_id'] = $this->Mkmgld->valid_user($data['surname_post']);
$surname = (isset($data['user_id'][0]->surname)? $data['user_id'][0]->surname: "");
if(isset($surname) and $surname !=NULL)
{
$data['query'] = $this->Mkmgld->get_kmgld($data['surname_post']);
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$data['set_cookie'] = $data['surname_post'];
$this->session->sess_destroy();
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->load->view('vfooter');
}else if (isset($surname_session) and $surname_session!= NULL)
{
//echo "you are in session";
$data['query'] = $this->Mkmgld->get_kmgld($surname_session);
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->load->view('vfooter');
} else
{
$data['flag'] = "wrong";
$this->load->view('vheader');
$this->load->view('vauthorisation',$data);
$this->load->view('vfooter');
}
//echo "<pre>";
//var_dump($data);
$this->output->enable_profiler(TRUE);
}//end authorisation_user()
function update_kmgld()
{
$this->load->model('Mkmgld');
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$trip_target_id = $data['get_trip_target_id'][0]->Auto_increment;
$this->Mkmgld->update_kmgld($this->input->post('day')
,$this->input->post('mon')
,$this->input->post('year')
,$this->input->post('spd_before')
,$this->input->post('spd_after')
,$this->input->post('total')
,$this->input->post('target')
,$this->input->post('approved')
,$this->input->post('user_id')
,$trip_target_id);
$a=$this->session->userdata('surname');
if ($a==NULL)
{
echo $a;
//redirect('kmgld/authorisation_user');
$this->output->enable_profiler(TRUE);
}
}
}//end class kmgld
?>
Model:
enter code here<?php
Class Mkmgld extends CI_Model {
function __construct()
{
parent::__construct();
}
function get_kmgld($surname){
$query = $this->db->query("SELECT
*
FROM `user`
INNER JOIN `user_has_trip`
ON `user`.`user_id` = `user_has_trip`.`user_id`
INNER JOIN `trip_target`
ON `user_has_trip`.`user_has_trip_id` = `trip_target`.`trip_target_id`
WHERE `user`.`surname` = '$surname'
");
return $query->result();
}
function valid_user($surname)
{
$user_id = $this->db->query("SELECT
*
FROM `user`
WHERE `user`.`surname`='$surname'
");
return $user_id->result();
}
function get_trip_target_id()
{
$get_trip_target_id = $this->db->query("SHOW TABLE STATUS LIKE 'trip_target'");
return $get_trip_target_id->result();
}
function update_kmgld($day, $mon, $year, $spd_before, $spd_after, $total, $target, $approved, $user_id, $trip_target_id)
{
$date = $year."-".$mon."-".$day;
$this->db->query("INSERT INTO `trip_target` (`trip_target_id`
,`date`
,`speedometer_before`
,`speedometer_after`
,`duration`
,`target`
,`approved`)
VALUES (NULL
,'$date'
,'$spd_before'
,'$spd_after'
,'$total'
,'$target'
,'$approved')
");
$this->db->query("INSERT INTO `user_has_trip`
(`user_has_trip_id`
,`user_id`
,`trip_target_id`
)
VALUES (NULL
,'$user_id'
,'$trip_target_id'
)
");
}
}//end class
?>
View vauthorisation:
<?php
$surname_value = $this->session->userdata('surname');
?>
<?php
if ($flag =="wrong")
{
echo "...Bad very bad. Try use another language ";
}
?>
html:
form method="post" action="authorisation_user"
input type="text" name="surname"
View vheader:
<?php
if ($set_cookie!=NULL)
{
$this->session->set_userdata('surname',$set_cookie);
echo "cookie set".$set_cookie;
}
?>
View vuser_kmgld:
html:
form action="update_kmgld"
inputs name=day, name=mon, name=year, name=spd_before...etc. After php code:
if (isset($user_id[0]->user_id))
{
foreach ($query as $row)
{
echo "<tr>
<td>".(isset($row->date)? date("d.m.Y", strtotime($row->date)): "")."</td>
<td>". (isset($row->speedometer_before)? $row->speedometer_before : "")."</td>
<td>". (isset($row->speedometer_after)? $row->speedometer_after : "")."</td>
<td>". (isset($row->duration)? $row->duration : "")."</td>
<td>". (isset($row->target)? $row->target : "")."</td>
<td>". (isset($row->aproved)? $row->aproved : "")."</td>
</tr>";
}
} //else redirect('kmgld/index');
?>

repopulating the select list generated from database in codeigniter

Hi. I have the form in which I use form_validation If the user make any mistake (leave some required fields empty), user is redirected back to the form, and the form has been re-populated. All works, except my select , which is generated from the database.
Here is my code from the view:
echo "<select name='parentid'" . set_value("parentid"). ">";
echo '<option value = "0">None</option>';
foreach ($faq_categories as $row => $option) {
echo "<option value=" . $option['catid'] . ">" . $option['categoryname']. "</option>";
}
echo '</select>';
Here is my controller code:
public function displayAddFaqCategoryForm($error = null)
{
$data['title'] = "Add new FAQ Category";
$data['main_content'] = 'addFaqCategory';
$selectWhat = array('tname' => 'faq_categories',
'sortby'=> 'catid',
'how' => 'asc'
);
$this->load->model('selectRecords');
$data['faq_categories'] = $this->selectRecords->selectAllRecords($selectWhat);
$this->load->vars($data);
$this->load->view('backOffice/template');
} // end of function displayAddFaqCategoryForm
And here is the model code:
public function selectAllRecords($selectWhat = array())
{
$data = array();
$tname = $selectWhat['tname'];
$sortby = $selectWhat['sortby'];
$how = $selectWhat['how'];
$this->db->order_by($sortby,$how);
$query = $this->db->get($tname);
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
$data[] = $row;
}
}
$query->free_result();
return $data;
} // end of function selectAllRecords
I am not getting any error messages, just the select is not repopulated with last used. Any help will be deeply appreciated.
You're using set_value() incorrectly
echo "<select name='parentid'" . set_value("parentid"). ">";
It's meant to output the actual value (for text inputs). This would produce something like:
<select name='parentid'ActualValue>
Which is not how a <select> element is populated, and is invalid HTML. See the correct usage in the Form Helper docs.
You can use set_select(), and it goes on your <option>:
foreach ($faq_categories as $row => $option) {
echo "<option value=".form_prep($option['catid']).'"';
echo set_select('parentid', $option['catid']); // outputs selected="selected"
echo ">".html_escape($option['categoryname'])."</option>";
}
I've taken a few other liberties with your code here as you can see, to be on the safe side (always).
If this is too much of a mess, you might be interested in the form_dropdown() function.

Resources