Add or edit data if already exist in database - php

Im trying to add or edit data depending if its already stored in the database. As you can see below im checking if user already exist with getuserid($id) loading the corresponding view but the problem is when i trigger add_user() or edit_user() as none of these methods are redirecting back as it should be. Any suggestions? This is the complete code http://pastebin.com/2G7D8ie4
public function getuserid($id = NULL){
if(!$id)
{
show_404();
}
$query = $this->Users_model->getuserid($id);
if($query == false){
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/add_users_view',
'id'=>$id);
}else{
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/edit_users_view',
'id'=> $query->id,
'staff_id'=> $query->staff_id,
'login'=> $query->login,
'password'=> $query->password
);
}
$this->load->view('themes/'.$this->config->item('theme_front').'.php', $data);
}
Model
public function getuserid($id){
$query = $this->db->get_where('users', array('staff_id' => $id));
if($query->num_rows() > 0){
return $query->row();
}else{
return false;
}
}

can you try making your model
public function getuserid($id){
$query = $this->db->get_where('users', array('staff_id' => $id));
$result=array();
foreach ($query->result() as $rows){
$result[]=$rows;
}
return $result;
}
and controller
if(count($query)>0){
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/edit_users_view',
'id'=> $query->id,
'staff_id'=> $query->staff_id,
'login'=> $query->login,
'password'=> $query->password
);
}
else
{
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/add_users_view',
'id'=>$id
);
}

Related

How to get and insert ID CodeIgniter

I save my data like this
public function saveInvestors($id = 0)
{
$data = array ('id' => $id );
$data2 = array ('ref_id' => $data['id]);
if ($id == 0)
{
return [$this->db->insert('investor', $data), $this->db->insert('leveling', $data2)];
}
}
my id on $data is auto increment on database while id on $data2 is not my problem here is that I couldn't get the id on $data and insert it on leveling but it always returning 0
You need to get the inserted id after inserting it into the database:
$this->db->insert('investor', $data);
$new_id = $this->db->insert_id();
As seen in the documentation: https://codeigniter.com/user_guide/database/helpers.html
Try this.
public function saveInvestors($id = 0)
{
$data = array('id' => $id);
if ($id == 0) {
$this->db->trans_begin();
$this->db->insert('investor', $data);
$id_investor = $this->db->insert_id();
$data2 = array('ref_id' => $id_investor);
$this->db->insert('leveling', $data2);
if ($this->db->trans_status() === TRUE) {
$this->db->trans_commit();
return TRUE;
} else {
$this->db->trans_rollback();
return FALSE;
}
}
}

if no row found in table add button should be display else edit using codeigniter

in a row record found means edit button should be display or add button and no row found in a table it should be display add button,i am getting a problem while no row in table displaying edit but i want display add button please refer my below code.
Controller
$result = $this->Profile_model->buyer_details();
$data['c_address'] = $result->address;
$data['c_pincode'] = $result->pincode;
$data['c_district'] = $result->district;
$data['c_city'] = $result->city;
$data['c_state'] = $result->state;
$data['c_country'] = $result->country;
$this->load->view('buyerdetails', $data);
Model code
public function buyer_details() {
$this->db->select('*');
$this->db->from('customer_otherdetails');
$this->db->where('customerid_fk', $this->session->id);
$query = $this->db->get();
$rows = $query->result(); //so you only have to call result once
// $rows = $query->result_array();
if ($query->num_rows() > 0) {
foreach ($rows as $row) {
//add all data to session
$newdataa = array(
'address' => $row->address,
'pincode' => $row->pincode,
'city' => $row->city,
'district' => $row->district,
'state' => $row->state,
'country' => $row->country,
);
}
$this->session->set_userdata('buyer', $newdataa);
//put the return outside the if
//return $query->result();
}
// return $rows; //this will be an empty array if no data found
return $query->row();
}
view page
<a onclick="hideHasSub()" data-toggle="collapse" data-parent="#accordion" href="#collapseone">
<?php
if (empty($c_country) == $this->session->userdata('buyer')) {
?>
<span class="profile-edit">Add</span>
<?php } else { ?>
<span class="profile-edit">Edit</span>
<?php } ?>
</a>
$this->db->where('customerid_fk', $this->session->id);
here change
$this->db->where('customerid_fk', $this->session->userdata('id');
now your model ::
public function buyer_details() {
$this->db->select('*');
$this->db->from('customer_otherdetails');
$this->db->where('customerid_fk', $this->session->userdata('id');
$query = $this->db->get();
$rows = $query->result(); //so you only have to call result once
// $rows = $query->result_array();
if ($query->num_rows() > 0) {
foreach ($rows as $row) {
//add all data to session
$newdataa = array(
'address' => $row->address,
'pincode' => $row->pincode,
'city' => $row->city,
'district' => $row->district,
'state' => $row->state,
'country' => $row->country,
);
}
$this->session->set_userdata('buyer', $newdataa);
//put the return outside the if
//return $query->result();
}
// return $rows; //this will be an empty array if no data found
return $query->row();
}
Use this code in "a" tag
<?php
if (empty($c_country[0]) || empty($c_country)){?>
<span class="profile-edit">Add</span>
<?php } else { ?>
<span class="profile-edit">Edit</span>
<?php } ?>

codeigniter update db with custom_result_object()

I got a codeigniter custom_result_object with this:
$user = $this->CI->db->get_where('users', array('email' => $email), 1)->custom_row_object(0,'entities\User');
and everything looks fine. I can update values with my setters.
Before I'm going to save i check my values with:
die(print_r($user));
and the values are correct.
I put my object in my update method.
$this->CI->db->update('users', $user, "id = ".$user->getId());
But the db is not updating. Am I missing something?
Thx!
EDIT:
So by using CI native db-method i can use:
public function save($user)
{
if($user->getId() == NULL){
$this->CI->db->insert('users', $user);
}else{
$this->CI->db->update('users', $user, "id = ".$user->getId());
}
}
Edit 2:
After some more checking I can see that it's not setting variables that are protected. CI is able to get the object through getters and setters but not able to save back to DB?
public function saveData($tbl,$data,$update = false,$previewStr = false){
$set_str = "NO_QUOTES()";
if(isset($data[$set_str])){
foreach($data[$set_str] as $set_key => $set_value){
$this->db->set($set_key, $set_value, FALSE);
}
unset($data[$set_str]);
}
if(isset($update[$set_str])){
foreach($update[$set_str] as $whr_key => $whr_value){
$this->db->where($whr_key." ".$whr_value,NULL,false);
}
unset($update[$set_str]);
if(is_array($update) and count($update) <= 0){
$update = true;
}
}
if($update == false){
$this->db->insert($tbl, $data);
if($previewStr){
return $this->db->last_query();
}else{
return $this->db->insert_id();
}
}else{
$result = NULL;
if(!is_array($update)){
if(is_array($data) and count($data) > 0){
foreach($data as $field => $value){
$this->db->set($field, $value);
}
}
$result = $this->db->update($tbl);
}else{
$result = $this->db->update($tbl, $data,$update);
}
if($previewStr){
return $this->db->last_query();
}else{
return $result;
}
}
}
public function delData($tbl = false,$where = array()){
if($tbl !== false){
return $this->db->delete($tbl, $where);
}else{
return false;
}
}
public function simpleQuery($query,$return_array = false,$return_single = false)
{
$ac = $this->db->query($query);
if($return_array === false){
return $ac;
}else{
if($return_single === false){
return $ac->result_array();
}else{
return $ac->row_array();
}
}
}
Use above code in your model and you i am giving you how to update it use below code in your controller you can insert update and delete by above code
$result=$this->Products_model->saveData("customer",array("customer_name"=>$name),array("cust_id"));

Having issues with count record in codeigniter

I am having a syntax issue in the controller in the function index where the view is being loaded. it is saying that I have Severity: Parsing Error
Message: syntax error, unexpected ';' I cannot figure out what the issue is I am trying to get the count of all my records in the database. Any help would be appreciated.
controllers/test.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Test extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('test_model','test_table');
}
public function index()
{
$this->load->view('includes/header');
$this->load->view('includes/table_main');
$this->load->view('includes/ajax_functions');
$this->load->view('includes/add_employee_form');
$total_records = $this->test_model->count_all_records();
//$this->load->view('test_view');
$this->load->view('test_view', array('total_records' => $total_records);
}
public function ajax_list()
{
$list = $this->test_table->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $test_table) {
$no++;
$row = array();
$row[] = $test_table->Name;
$row[] = $test_table->Department;
$row[] = $test_table->Manager;
//add html for action
$row[] = '<a class="btn btn-sm btn-link " href="javascript:void()" title="Edit" onclick="edit_test('."'".$test_table->id."'".')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>
<a class="btn btn-sm text-warning" href="javascript:void()" title="Hapus" onclick="delete_test('."'".$test_table->id."'".')"><i class="glyphicon glyphicon-trash"></i> Delete</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->test_table->count_all(),
"recordsFiltered" => $this->test_table->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
public function ajax_edit($id)
{
$data = $this->test_table->get_by_id($id);
echo json_encode($data);
}
public function ajax_add()
{
$this->_validate();
$data = array(
'Name' => $this->input->post('Name'),
'Department' => $this->input->post('Department'),
'Manager' => $this->input->post('Manager'),
);
$insert = $this->test_table->save($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_update()
{
$this->_validate();
$data = array(
'Name' => $this->input->post('Name'),
'Department' => $this->input->post('Department'),
'Manager' => $this->input->post('Manager'),
);
$this->test_table->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
public function ajax_delete($id)
{
$this->test_table->delete_by_id($id);
echo json_encode(array("status" => TRUE));
}
//validation section were user must enter data in all fields
private function _validate()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('Name') == '')
{
$data['inputerror'][] = 'Name';
$data['error_string'][] = 'Name is required';
$data['status'] = FALSE;
}
if($this->input->post('Department') == '')
{
$data['inputerror'][] = 'Department';
$data['error_string'][] = 'Department is required';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
}
Model
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class test_model extends CI_Model {
var $table = 'test_table';
var $column = array('Name','Department','Manager'); //set column field database for order and search
var $order = array('id' => 'desc'); // default order
public function __construct()
{
parent::__construct();
$this->load->database();
}
private function _get_datatables_query()
{
$this->db->from($this->table);
$i = 0;
foreach ($this->column as $item) // loop column
{
if($_POST['search']['value']) // if datatable send POST for search
{
if($i===0) // first loop
{
$this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
$this->db->like($item, $_POST['search']['value']);
}
else
{
$this->db->or_like($item, $_POST['search']['value']);
}
if(count($this->column) - 1 == $i) //last loop
$this->db->group_end(); //close bracket
}
$column[$i] = $item; // set column array variable to order processing
$i++;
}
if(isset($_POST['order'])) // here order processing
{
$this->db->order_by($column[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else if(isset($this->order))
{
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function count_all_records(){
$this->db->select('id');
$this->db->distinct();
$this->db->from('test_table');
$query = $this->db->get();
return $query->num_rows();
}
function get_datatables()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
function count_filtered()
{
$this->_get_datatables_query();
$query = $this->db->get();
return $query->num_rows();
}
public function count_all()
{
$this->db->from($this->table);
return $this->db->count_all_results();
}
public function get_by_id($id)
{
$this->db->from($this->table);
$this->db->where('id',$id);
$query = $this->db->get();
return $query->row();
}
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
public function update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
public function delete_by_id($id)
{
$this->db->where('id', $id);
$this->db->delete($this->table);
}
}
view
Total Records: <?php echo $total_records ?>
In the class Test index function last statement ) is missing. Here is the correct one
$this->load->view('test_view', array('total_records' => $total_records));
It might cause due to script contain in view ,set short_open_tag 0 in your htaccess file and check if solves
<IfModule mod_php5.c >
php_value short_open_tag 0
</IfModule >

Codeigniter get all rows from db

I'm working on task manager where have 2 types of user: Administrators(all privileges), and Users(limited privileges).
Here's my task function in controller
function task($id) {
$data = array(
'query' => $this->main_model->get_task($id),
'task_id' => $id,
);
$data2['comments'] = $this->main_model->get_comments($id);
$this->load->library('form_validation');
$this->load->helper('security');
$this->form_validation->set_rules('comment_text', 'comment_text', 'trim|required|strip_tags|xss_clean');
if ($this->form_validation->run() === FALSE)
{
if($this->main_model->get_task($id))
{
foreach ($this->main_model->get_task($id) as $tas)
{
$data = array(
'title' => $tas->task_name,
'desc' => $tas->task_description,
'date_created' => $tas->date,
'date_started' => $tas->task_start_date,
'deadline' => $tas->task_deadline,
'creator' => $tas->task_creator,
'owner' => $tas->task_owner,
'attach'=>$tas->attachment_name,
'status'=>$tas->task_status,
'priority'=>$tas->task_priority,
'task_id'=>$tas->ID_task,
'base_url' => base_url()
);
}
$data1 = array(
'emps' => $this->main_model->get_employees(),
'creator' => $this->main_model->get_details($id),
'owner' => $this->main_model->get_owner($id)
);
if ($this->session->userdata('employee_type') == 3) {
$qu = $this->main_model->permission();
$id = $this->session->userdata('id');
$id_emp = $this->uri->segment(3);
//foreach ($qu as $q) {
if (in_array($id, $qu[0]) && in_array($id_emp, $qu[0])) {
$this->load->view('task', array_merge($data, $data1, $data2));
}
else {
echo "No Permission to access this task";
}
}
}
}
else
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'doc|docx|pdf|txt|text|rtf|jpg|gif|png';
$config['max_size'] = '1024';
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
if ("You did not select a file to upload." != $this->upload->display_errors('','')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('task', $error);
}
else {
$this->main_model->set_comments($id);
redirect(current_url());
}
}
else {
$data = array('upload_data' => $this->upload->data());
$data1 = $this->upload->data();
$data2 = $data1['file_name'];
$this->main_model->set_comments($id);
$this->main_model->set_attachment($id, $data2);
redirect(current_url());
}
}
}
and my permission function in model:
function permission() {
$query = $this->db->get('employees_tasks');
$ret = $query->result_array();
return $ret;
}
What I'm trying to do is, get all data from database employee_tasks check if the ID_task and ID_employee are in the same row in database, but I can't get it working, I only getting first row of database, not the others, and that's my key problem, get all rows from db.
I tried query database with result, result_array, row, row_array, but for some reason everything is listing only first row in db. Any Help would be appreciated.
To get all results from a separate table using codeigniter Active record you can do like this
function permission() {
$this->db->select("*");
$this->db->from("employees_tasks");
$this->db->where('id', 'your id');
$query = $this->db->get();
return $query->result();
// OR
$query = $this->db->query("SELECT * from employees_tasks WHERE your condition");
return $query->result();
}
Hope it makes sense

Categories