codeigniter - display data from data base in dropdown [duplicate] - php

This question already has answers here:
Ajax drop down for Country State & City in Codeigniter?
(3 answers)
Closed 8 years ago.
i am creating an application in codeigniter for the form we want country and state in drop down on change selection of country
Controller is like
public function user()
{
$data = array();
$this->load->model('enquiry');
$this->load->helper('url');
$data['result'] = $this->enquiry->get_reqtutor();
$data['countries'] = $this -> country_model -> get_countries();
$this->load->view('Table\DemoHistory',$data);
}
function get_states($country) {
$this->load->helper('url');
$this->load->model('state_model');
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($this->state_model->get_states($country)));
}
and model is like
state_model`
<?php
class State_model extends CI_Model {
public function __construct() {
$this -> load -> database();
}
function get_states($country = null){
$this->db->select('state_id, state_name');
if($country != NULL){
$this->db->where('country_id', $country);
}
$query = $this->db->get('state_master');
$states = array();
if($query->result()){
foreach ($query->result() as $state) {
$cities[$state->state_id] = $state->state_name;
}
return $states;
} else {
return FALSE;
}
}
}
?>
country_model
<?php
class Country_model extends CI_Model {
public function __construct() {
$this -> load -> database();
}
function get_countries() {
$this -> db -> select('country_id, country_name');
$query = $this -> db -> get('country_master');
$countries = array();
if ($query -> result()) {
foreach ($query->result() as $country) {
$countries[$country -> country_id] = $country -> country_name;
}
return $countries;
} else {
return FALSE;
}
}
}
?>
Ajax is like
<script type="text/javascript">// <![CDATA[
$(document).ready(function(){
$('#country').change(function(){ //any select change on the dropdown with id country trigger this code
$("#cities > option").remove(); //first of all clear select items
var country_id = $('#country').val(); // here we are taking country id of the selected one.
$.ajax({
type: "POST",
url: /mtb/Schedule/get_states/"+country_id, //here we are calling our user controller and get_cities method with the country_id
success: function(cities) //we're calling the response json array 'cities'
{
$.each(cities,function(state_id,state_name) //here we're doing a foeach loop round each city with id as the key and city as the value
{
var opt = $('<option />'); // here we're creating a new select option with for each city
opt.val(state_id);
opt.text(state_name);
$('#cities').append(opt); //here we will append these new select options to a dropdown with the id 'cities'
});
}
});
});
});
// ]]>
</script>
and view is
<?php $countries['#'] = 'Please Select'; ?>
<label for="country">Country: </label><?php echo form_dropdown('country_id', $countries, '#', 'id="country"'); ?>
<?php $cities['#'] = 'Please Select'; ?>
<label for="city">State: </label><?php echo form_dropdown('state_id', $cities, '#', 'id="cities"'); ?>
i am getting country name while my state value is not comming in dropdown please help........

Things to consider about your code:
You have an error here url: /mtb/Schedule/get_states/"+country_id, missing double quote at the beggining. Always use a debugging tool, like firebug, it will show you the javascript errors.
Another thing, the code
if($country != NULL){
should be
if(!is_null($country)){
take a look at is_null function.
Another thing, instead of application/x-json json header you should use application/json.
Another thing, the code
echo(json_encode($this->state_model->get_states($country)));
should be
echo(json_encode($this->state_model->get_states($country)));
exit;
otherwise unexpected result might be appended to the final json. Example: CodeIgniter profiling.
Another thing, the code
$countries = array();
if ($query -> result()) {
foreach ($query->result() as $country) {
$countries[$country -> country_id] = $country -> country_name;
}
return $countries;
} else {
return FALSE;
}
should be
$countries = array();
foreach ($query->result() as $country) {
$countries[$country -> country_id] = $country -> country_name;
}
return $countries;
because having no countries and returning FALSE will give you an error in form_dropdown function, take a look inside it. The same goes for get_states function.
This is how much I see in a preliminary look of your code.

Related

Getting parameter value from $resource in Angular using PHP

I'm trying to retrieve data from my Wordpress database using an Angular factory. Using ng-click="updateCommentsById(v.id.videoId)" I call the following function:
$scope.updateCommentsById = function(id) {
commentRepository.query(({videoId: id}), function (data) {
$scope.comments = data;
});
}
That corresponds to the following factory definition:
angular.module("app")
.factory("commentRepository",
function($resource) {
return $resource("/wp-content/themes/zerif-lite-child/inc/get_comments.php/:videoId",
{
videoId:"#id"
});
});
The problem is how to get the videoId parameter into my PHP function inside get_comments.php:
<?php
require_once($_SERVER["DOCUMENT_ROOT"]."/wp-load.php");
function get_comments_by_id($id)
{
echo $id;
if (!is_user_logged_in()) {
echo json_encode("Not Authorised");
} else {
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM analyser_posts WHERE video_id = $id", OBJECT);
echo wp_json_encode($result);
}
}
get_comments_by_id(videoId);
EDIT:
Turns out the get_results() method doesn't allow variables inside SQL statements, I should use prepare() (safer anyway) instead. I also changed the request URL. The new code becomes:
angular.module("app")
.factory("commentRepository",
function ($resource) {
return $resource("/wp-content/themes/zerif-lite-child/inc/get_comments.php?video_id=:videoId");
});
and PHP:
<?php
require_once($_SERVER["DOCUMENT_ROOT"]."/wp-load.php");
function get_comments_by_id($id)
{
var_dump($id);
if (!is_user_logged_in()) {
echo json_encode("Not Authorised");
} else {
global $wpdb;
$result = $wpdb->prepare("SELECT * FROM analyser_posts WHERE video_id = $id", OBJECT);
var_dump($result);
$result_array = array();
if($result){
foreach($result_array as $r){
$result_array[] = $r;
}
}
var_dump($result_array);
echo json_encode($result_array);
}
}
get_comments_by_id($_GET["video_id"]);
However the var_dumps show that the id gets passed correctly, only the prepare() doesn't actually execute anything. Should I wrap that in a get_results?
You could extract it from the URI:
//$args is an array of every part separated by `/` (ignoring the query string)
$args = explode('/',strtok(trim($_SERVER['REQUEST_URI'],'/'),'?'));
//the last element is the video id
$video_id = end($args);
Live demo
Got it to work using the answers (including those now removed) and comments. The function inside my Angular controller code:
$scope.updateCommentsById = function(id) {
commentRepository.query(({videoId: id}), function (data) {
$scope.comments = data;
});
}
Repository:
angular.module("app")
.factory("commentRepository",
function ($resource) {
return $resource("/wp-content/themes/zerif-lite-child/inc/get_comments.php?video_id=:videoId");
});
get_comments.php:
<?php
require_once($_SERVER["DOCUMENT_ROOT"]."/wp-load.php");
function get_comments_by_id($id)
{
if (!is_user_logged_in()) {
echo json_encode("Not Authorised");
} else {
global $wpdb;
$sql = $wpdb->prepare("SELECT * FROM `analyser_posts` WHERE `video_id` = '$id'", OBJECT);
$result = $wpdb->get_results($sql);
echo json_encode($result);
}
}
get_comments_by_id($_GET["video_id"]);

Ajax request in MVC doesn't return corresponding value to the HTML page

Below is my script in Dashboard module.
$(function()
{
var o;
$.get('dashboard/xhrgetInsert',function(o)
{
for(var i = 0;i <= o.length; i++)
{
$("#appendHere").append("<div>"+o[i].text+"</div>");
}
},'json');
$("#randomInsert").submit(function()
{
alert("hi");
var data = $(this).serialize();
var url = $(this).attr("action");
$.post(url,data,function(o)
{
$("#appendHere").append("<div>"+o+"</div>");
},'json');
return false;
});
});
Supposedly, when I'm in the dashboard page this function(xhrgetInsert) has to return value to be appended in the HTML. Unfortunately, it doesn't append anything and as I checked in the chrome console 'response'..it says method doesn't exist. But If I type the method name in the url, it shows the values returned in json format as I specified so.
Same goes for 'xhrInsert()' function as it doesn't return value to be appended. Database connection is perfect as it can insert and select data from db just unable get back the values..
I'm wondering first, why it says the method doesn't exist, and secondly why doesn't return any value?
My 'Dasboard controller making call to dashboard model'
public function xhrInsert()
{
$this->model->xhrInsert();
}
public function xhrgetInsert()
{
$this->model->xhrgetInsert();
}
Dashboard model contains mysql queries to the database whcih return values in jason format
public function xhrInsert()
{
$text = $_POST['text'];
$sql = $this->db->prepare("INSERT INTO data(text)VALUES(:text)");
$sql->execute(array(':text'=>$text));
echo json_encode($text);
}
public function xhrgetInsert()
{
$sth = $this->db->prepare("SELECT * FROM data");
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
$data = $sth->fetchAll();
echo json_encode($data);
}
Finally, this is my HTML for dashboard
<h1>Dashboard</h1>
<form id="randomInsert" action="<?php echo URL;?>dashboard/xhrInsert" method="post">
<label>Text: </label><input type="text" name="text"/><br/>
<input type="submit"/>
</form>
<div id="appendHere"></div>
Console Screenshot
Function should return the result json data to ajax request so it won't render the whole html page with result.
public function xhrInsert(){
echo $this->model->xhrInsert();
die;
}
public function xhrgetInsert()
{
echo $this->model->xhrgetInsert();
die;
}
Model
public function xhrInsert()
{
$text = $_POST['text'];
$sql = $this->db->prepare("INSERT INTO data(text)VALUES(:text)");
$sql->execute(array(':text'=>$text));
return json_encode($text);
}
public function xhrgetInsert()
{
$sth = $this->db->prepare("SELECT * FROM data");
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
$data = $sth->fetchAll();
return json_encode($data);
}

getting values of second select from db based of first select box selection in codeigniter

I Need help on how can i get values of second select box based on first select box
This is view:
$(document).ready(function() {
$('#state').change(function() {
// Get an instance of the select, and it's value.
var state = $(this),
stateID = state.val();
// Add if statement to check if the new state id
// is different to the last to prevent loading the same
// data again.
// Do the Ajax request.
$.ajax({
url : 'http://localhost/ci_ajax/select/get_cities/'+stateID, // Where to.
dataType : 'json', // Return type.
success : function(data) { // Success :)
// Ensure we have data first.
if(data && data.Cities) {
// Remove all existing options first.
state.find('option').remove();
// Loop through each city in the returned array.
for(var i = 0; i <= data.Cities.length; i++) {
// Add the city option.
state.append($('option').attr({
value : data.Cities[i].value
}).text(data.Cities[i].city));
}
}
},
error : function() {
// Do something when an error happens?
}
});
});
});
<form action="" method="post">
<select name="state" id="state">
<option>Select</option>
<?php foreach($states as $row):?>
<option value="<?php echo $row->id?>"><?php echo $row->states;?></option>
<?php endforeach;?>
</select>
<select id="cities" name="cities">
<option>Select</option>
</select>
This is controller:
class Select extends CI_Controller{
function index(){
$data['states']=$this->load_state();
$this->load->view('form',$data);
}
function load_state(){
$this->load->model('data_model');
$data['states']=$this->data_model->getall_states();
return $data['states'];
}
function get_cities() {
// Load your model.
$this->load->model('data_model');
// Get the data.
$cities = $this->data_model->get_cities();
// Specify that we're returning JSON.
header('content-type: application/json');
// Return a JSON string with the cities in.
return json_encode(array('Cities' => $cities));
}
}
This is model:
class Data_model extends CI_Model{
function getall_states(){
$query=$this->db->get('states');
if($query->num_rows()>0){
foreach($query->result() as $row){
$data[]=$row;
}
return $data;
}
}
function get_cities(){
$this->db->select('id,cities');
$this->db->from('cities');
$this->db->where('s_id',$this->uri->segment(3));
$query=$this->db->get();
if($query->num_rows()>0){
foreach($query->result() as $row){
$data[]=$row;
}
return $data;
}
}
}
Please help on this hopefully provide the correct code.
Because you are accessing the get_cities() function directly, rather than from another function in the controller, your return statement will not actually print the json array to the page.
return json_encode(array('Cities' => $cities));
There are 3 ways to print it: the first is to print or echo the json array (bad practice), the second is to use a view that prints the raw text sent to it. I.E.
$this->load->view('raw', array('data' => json_encode(array('Cities' => $cities)));
With raw.php being just:
<?php print $data; ?>
Or finally you can use the set_output() function in the output class like this:
$this->output->set_output(array('data' => json_encode(array('Cities' => $cities)));
You may also want to make your function load_state() private if it is only going to be accessed from the index() function.
You may have other problems with your code but that is the most obvious one.

jquery ui's"selectable" - need to call codeigniter model function

(Original Questions) I am using jquery ui's selectable script to control specific active keywords in my webapp. View here: www.rickymason.net/letschat/main/home for reference
I have very little experience with javascript and I'm trying to figure out how to launch a function I have in my main model.
Updated function based on answers:
I have updated my code to support the new JSON/AJAX format. This required me to create an active/inactive session filter so that the user can add filters normally, and always use AJAX to update the thread list. This just made more sense to me.
Here is the code I have currently, which still is not working. I am attempting to make it so when the user clicks on a selectable category (through Jquery UI), the divID associated with the selection is passed through AJAX and returns a threadlist array that updates the div id ="board".
Here is my current Controller set up:
public function home($page = 'home')
{
$data['user_id'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
$data['threads'] = $this->thread_model->session_load();
$data['title'] = ucfirst($page); // Capitalize the first letter
$data['page'] = $page;
$this->load->view('templates/head', $data);
$this->load->view('templates/nav', $data);
$this->load->view('main/newthread', $data);
$this->load->view('main/addfilter', $data);
$this->load->view('main/checkbox', $data);
$this->load->view('main/displayfilter',$data);
$this->load->view('main/board', $data);
$this->load->view('templates/footer');
}
public function updatefilters($filters)
{
$filterarray = split("|", $filters);
$this->thread_model->create_session_filter($filterarray);
$threadarray = $this->thread_model->get_threads();
$data['json'] = '{"content":' + $threadarray + '}';
$this->load->view('json_view', $data); // See step 4!!!
}
Here is my current model code:
public function get_threads()
{
$filter = $this->session->userdata('filter');
$num_tags = count($filter);
if ($num_tags > 0 && $num_tags <= 8) {
$sql_select = "SELECT DISTINCT t.* ";
$sql_from = " FROM ";
$sql_where = " WHERE ";
$sql_joins = "";
$sql_order = "ORDER BY t.timestamp DESC";
for ($i=0;$i<$num_tags;++$i) {
if ($i==0) {
$sql_from .= " filter AS f ";
$sql_where .= " f.tag LIKE '%" . $filter[0] . "%'";
$sql_joins .= " INNER JOIN filter_thread AS ft ON ft.filter_id = f.filter_id
INNER JOIN thread AS t ON ft.thread_id = t.thread_id";
}
else {
$sql_where .= " OR f.tag LIKE '%" . $filter[$i] . "%'";
}
}
} else {
break;
}
$sql = $sql_select . $sql_from . $sql_joins . $sql_where . $sql_order;
$query = $this->db->query($sql);
$thread = $query->result_array();
return json_encode($thread); //I am aware this is not correct
}
public function create_session_filter($filterstring)
{
$filterarray[] = $filterstring;
$filter['filter'] = $filterarray;
if ($this->session->userdata('filter') == TRUE) {
$sessionfilter = $this->session->userdata('filter');
$new = array_merge($sessionfilter, $filter['filter']);
$this->session->unset_userdata('filter');
$filter['filter'] = $new;
$this->session->set_userdata($filter);
} else {
if (!$filterstring) {} else {
$this->session->set_userdata($filter);
}
}
}
public function create_session_inactive_filter($filterstring)
{
$filterarray[] = $filterstring;
$filter['inactivefilter'] = $filterarray;
if ($this->session->userdata('inactivefilter') == TRUE) {
$sessionfilter = $this->session->userdata('inactivefilter');
$new = array_merge($sessionfilter, $filter['inactivefilter']);
$this->session->unset_userdata('inactivefilter');
$filter['inactivefilter'] = $new;
$this->session->set_userdata($filter);
} else {
if (!$filterstring) {} else {
$this->session->set_userdata($filter);
}
}
}
And here is my current view code:
application/main/json_view.php
<?php
header("Content-Type: application/json");
echo $json;
?>
aplication/main/bdisplayfilter.php
<script>
$(function() {
$( "#selectable" ).selectable({
selected: updateFilters,
unselected: updateFilters
});
function updateFilters(ev, ui){
alert ("hello");
// get the selected filters
var $selected = $('#selectable').children('.ui-selected');
// create a string that has each filter separated by a pipe ("|")
var filters = $selected.map(function(){return this.id;}).get().join("|");
$.ajax({
url: '/main/updateFilters', //see step 2
data: { filters: filters },
success: function(data){
// data is whatever json you decide to return from the server.
// An easy way to do things is have data look like this:
// { content: "<div>All my new threads that I want to show up</div>" }
// then, you can replace some element on the page with the new content
// For example, say your container has an id of threadContainer:
$('#select').replaceWith(data.content);
}
}); }
});
</script>
<ol id="selectable">
<li class="ui-state-default" id="everything">Everything!</li>
<li class="ui-state-default" id="entertainment">Entertainment</li>
<li class="ui-state-default" id="sci/tech">Sci/Tech</li>
<li class="ui-state-default" id="news">News</li>
<?php
if ($this->session->userdata('inactivefilter') == true) {
$inactivefilter = $this->session->userdata('inactivefilter');
foreach ($inactivefilter as $new)
{
echo "<li class='ui-state-default' id='custom'>$new</li>";
}
}
?>
</ol>
<?php
if ($this->session->userdata('inactivefilter') == true) {
echo "<form action='".base_url()."main/clear_filter'><input type='submit' value=clear></form>";
} ?>
EDIT: I've updated the url and data parts of the ajax call and added an additional step to enable query string parameters.
1) Make the AJAX call
You will want to make the same call for selected and unselected, since you can have multiple filters and you need things to update accordingly on both events. So, I'll define a common function that both events can call.
$(function() {
$( "#selectable" ).selectable({
selected: updateFilters,
unselected: updateFilters
});
function updatefilters(ev, ui){
// get the selected filters
var $selected = $('#selectable').children('.ui-selected');
// create a string that has each filter separated by a pipe ("|")
var filters = $selected.map(function(){return this.id;}).get().join("|");
$.ajax({
url: '/index.php',
data: { c: main, m: updateFilters, filters: filters },
success: function(data){
// data is whatever json you decide to return from the server.
// An easy way to do things is have data look like this:
// { content: "<div>All my new threads that I want to show up</div>" }
// then, you can replace some element on the page with the new content
// For example, say your container has an id of threadContainer:
$('#threadContainer').replaceWith(data.content);
}
});
}
});
2) Enable query string parameters in application/config.php
The section called Enabling Query Strings at the bottom of this article explains how to do that:
http://codeigniter.com/user_guide/general/urls.html
3) Create an action that will receive the filters
Note that I'm using a controller called Page (which would live in /application/controllers/page.php). This action (updateFilters) could live in any controller you want.
class Page extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
}
function updateFilters($filters)
{
$filterarray = split("|", $filters);
create_session_filter($filterarray);
$articlesHTML = getThreadList($filterarray); // See step 4!!!
$data['json'] = '{"content":' + $articlesHTML + '}';
$this->load->view('json_view', $data); // See step 5!!!
}
/* I've updated this slightly to accept an array */
public function create_session_filter($filterarray)
{
$filter['filter'] = $filterarray;
//... the rest of your stuff you already had
}
}
4) Implement getThreadList method
I don't think you mentioned if you already had something set up for this. This would basically take an array of filters and then render a thread list based off that.
5) Create json_view (if not already there)
This will set the content type so that the browser knows the content is json.
In /application/views/json_view.php:
<?php
header("Content-Type: application/json");
echo $json;
?>

Fatal error: Call to a member function num_rows() on a non-object [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
Hihow r u all?
I m trying to calculate basic salary with Particular employee_id but when i m trying to .. give me fatal error..
Fatal error: Call to a member function num_rows() on a non-object in D:\wamp\www\template\application\models\salary.php on line 112
my code is: model
<?php
class Salary extends Model
{
/*
Determines if a given person_id is a profile
*/
function exists($salary_id)
{
$this->db->from('salary_scale');
$this->db->where('id',$salary_id);
$this->db->where('deleted',0);
$query = $this->db->get();
return ($query->num_rows()==1);
}
/*
Determines if a given employee_id is a employee
*/
function exists_employee($employee_id)
{
$this->db->from('grade_history');
$this->db->where('employee_id',$employee_id);
$query = $this->db->get();
return ($query->num_rows()==1);
}
/*
Returns all the suppliers
*/
function get_all()
{
$this->db->from('salary_scale');
$this->db->where('deleted', 0);
$this->db->order_by("name", "asc");
return $this->db->get();
}
/*
*
* Gets information about a particular employees salary
*/
function grade_rules_info($salary_grade)
{
$this->db->from('salary_scale_rules');
$this->db->where('salary_grade',$salary_grade);
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row();
}
else
{
//Get empty base parent object, as $item_id is NOT an item
$salary_obj=new stdClass();
//Get all the fields from items table
$fields = $this->db->list_fields('salary_scale_rules');
foreach ($fields as $field)
{
$salary_obj->$field='';
}
return $salary_obj;
}
}
/*
*
* Gets information about a particular employees salary
*/
function get_info($employee_id)
{
$this->db->from('allowance');
//$this->db->join('deductions', 'deductions.eid = allowance.eid');
$this->db->where('employee_id',$employee_id);
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row();
}
else
{
//Get empty base parent object, as $item_id is NOT an item
$salary_obj=new stdClass();
//Get all the fields from items table
$fields = $this->db->list_fields('items');
foreach ($fields as $field)
{
$salary_obj->$field='';
}
return $salary_obj;
}
}
/**
* Gets information about a particular employees salary
*
**/
function get_grade_info($employee_id)
{
$this->db->from('grade_history');
$this->db->where('employee_id',$employee_id);
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row();
}
else
{
//Get empty base parent object, as $employee_id is NOT an employee
$grade_obj=new stdClass();
//Get all the fields from items table
$fields = $this->db->list_fields('grade_history');
foreach ($fields as $field)
{
$grade_obj->$field='';
}
return $grade_obj;
}
}
/**
* Inserts or updates configuration data
*
*/
function save_grade(&$data, $employee_id=false)
{
if (!$employee_id)
{
if($this->db->insert('grade_history', $data))
{
$data['id']=$this->db->insert_id();
return true;
}
return false;
}
$this->db->where('id', $employee_id);
return $this->db->update('grade_history', $data);
}
// ------------------------ End of save_salary_cinfig function -----------------------------
/*
* Basic pay salary calculation
*/
function basic_pay($employee_id)
{
// Get grade information from grade_history table
// Get Particular person grade ifnormation by employ_id
$grade_info = $this->get_grade_info($employee_id);
$salary_grade = $grade_info->salary_grade;
$no_of_increment = $grade_info->number_of_increment;
// Get Grade rules information about particular grade by passing $salary_grade number
$grade_rules = $this->grade_rules_info($salary_grade);
$basic_amount = $grade_rules->basic_amount;
$increment = $grade_rules->increment;
$max_no_of_increment = $grade_rules->number_of_increment;
$max_amount = $grade_rules->max_amount;
return $basic_pay = $basic_amount + $increment*$no_of_increment;
}
}
?>
controller
<?php
require_once ("secure_area.php");
class Salaries extends Secure_area
{
function __construct()
{
parent::__construct('salaries');
}
function index()
{
$data['controller_name']=strtolower($this->uri->segment(1));
$data['form_width']=$this->get_form_width();
$data['manage_table']=get_profile_manage_table($this->Profile->get_all(),$this);
$this->load->view('salaries/manage',$data);
}
/*
Returns profile table data rows. This will be called with AJAX.
*/
function search()
{
$search=$this->input->post('search');
$data_rows=get_profile_manage_table_data_rows($this->Profile->search($search),$this);
echo $data_rows;
}
/*
Gives search suggestions based on what is being searched for
*/
function suggest()
{
$suggestions = $this->Profile->get_search_suggestions($this->input->post('q'),$this->input->post('limit'));
echo implode("\n",$suggestions);
}
/*
Loads the profile form
*/
function view($employee_id=-1)
{
//$data['salary_summary_info'] =$this->Salary->get_info($salary_id);
//$data['salary_deductions_summary_info'] =$this->Salary->get_deductions_info($salary_id);
$employee_id = array('' => '-- Select Employee ID --');
foreach($this->Profile->get_employee_id()->result_array() as $row)
{
$employee_id[$row['employee_id']]= $row['employee_id'];
}
$data['employee_id'] = $employee_id;
// $data['selected_employee_id'] = $this->Profile->get_info($employee_id)->employee_id;
$data['basic_pay'] = $this->Salary->basic_pay($employee_id);
$this->load->view("salaries/salary_summary_form", $data);
}
//--------------------------------------End view function-----------------------------------
/*
Loads the profile form
*/
function grade_view($employee_id=-1)
{
$data['salary_grade_info'] = $this->Salary->get_grade_info($employee_id);
$data['basic_pay'] = $this->Salary->basic_pay($employee_id);
$this->load->view("salaries/grade_view", $data);
}
//--------------------------------------End view function-----------------------------------
/*
Inserts/updates a profile
*/
function save_salary_grade($id=-1)
{
$grade_data = array(
'eid' =>$this->input->post('employee_id'),
'salary_grade' =>$this->input->post('salary_grade'),
'number_of_increment' =>$this->input->post('number_of_increment'),
'comments' =>$this->input->post('comments'),
'date' =>date('Y-m-d H:i:s')
);
if($this->Salary->save_grade($grade_data, $id))
{ //New profile
if($id==-1)
{
echo json_encode(array('success'=>true,'message'=>$this->lang->line('profiles_successful_adding').' '.
$grade_data['salary_grade'].' '.$grade_data['number_of_increment'],'id'=>$grade_data['eid']));
}
else //previous profile
{
echo json_encode(array('success'=>true,'message'=>$this->lang->line('profiles_successful_updating').' '.
$grade_data['salary_grade'].' '.$grade_data['number_of_increment'],'id'=>$grade_data['eid']));
}
}
else//failure
{
echo json_encode(array('success'=>false,'message'=>$this->lang->line('profiles_error_adding_updating').' '.
$grade_data['salary_grade'].' '.$grade_data['number_of_increment'],'id'=>$grade_data['id']));
}
}
/*
This deletes profiles from the profiles table
*/
function delete()
{
$profiles_to_delete=$this->input->post('ids');
if($this->Profile->delete_list($profiles_to_delete))
{
echo json_encode(array('success'=>true,'message'=>$this->lang->line('profiles_successful_deleted').' '.
count($profiles_to_delete).' '.$this->lang->line('profiles_one_or_multiple')));
}
else
{
echo json_encode(array('success'=>false,'message'=>$this->lang->line('profiles_cannot_be_deleted')));
}
}
/*
get the width for the add/edit form
*/
function get_form_width()
{
return 900;
}
}
?>
and view
<?php
echo form_open('salaries/save/'.$employee_id, array('id'=>'salary_summary_form'));
//echo form_open('salaries/save/', array('id'=>'salary_summary_form'));
?>
<div id="required_fields_message"><?php echo $this->lang->line('common_fields_required_message'); ?></div>
<ul id="error_message_box"></ul>
<fieldset id="salary_allowance_info">
<legend><?php echo $this->lang->line("salaries_allowance_info"); ?></legend>
<div class="field_row clearfix">
<?php echo form_label($this->lang->line('salaries_employee_id').':', 'employee_id', array('class'=>'required')); ?>
<div class='form_field'>
<?php echo form_dropdown('employee_id', $employee_id);?>
</div>
</div>
<div class="field_row clearfix">
<?php echo form_label($this->lang->line('salaries_allowance_basic_salary').':', 'basic_salary', array('class'=>'required')); ?>
<div class='form_field'>
<?php echo form_input(array(
'name'=>'basic_salary',
'id'=>'basic_salary',
'value'=>$basic_pay
));
?>
</div>
</div>
<div class="field_row clearfix">
<?php echo form_label($this->lang->line('salaries_allowance_house_rent').':', 'house_rent',array('class'=>'required')); ?>
<div class='form_field'>
<?php echo form_input(array(
'name'=>'house_rent',
'id'=>'house_rent',
// 'value'=>$salary_summary_info->house_rent
));
?>
</div>
</div>
<?php
echo form_submit(array(
'name'=>'submit',
'id'=>'submit',
'value'=>$this->lang->line('common_submit'),
'class'=>'submit_button float_right')
);
?>
</fieldset>
<?php
echo form_close();
?>
pls help me if any one
You don't test if your call to $db -> get() succeeded. I don't know the details of your $db class, but I suspect it only returns something if the call to it was successful. If the query fails does $db -> get() still return something?
Try doing a var_dump on what you get out of $db -> get() so you can see if it's returning what you think it's returning.
Fatal error: Call to a member function num_rows() on a non-object... is usually because there were no results return from a given query or possibly from a bad query.

Categories