I have this code:
public function getJccLineItem($id,$action)
{
$res = array();
$q = 'SELECT * FROM jcc_line_items jli,ipo_line_item ili ,line_items li
WHERE jli.line_item_id= ili.id and li.id = jli.line_item_id
and ili.dn_number_id in ( Select dn_number from ipo where project_id= '.$id.')';
$res = $this->db->query($q);
echo $this->db->last_query();
$jccLineItemArray = array();
echo $id;
print_r($res->result());
if($action == 'array')
{
foreach ( $res->result() as $key => $value) // The error comes in this line
{
$jccLineItemArray[ $value->id ] = $value->item_description;
}
$res = $jccLineItemArray;
}
else
{
$res = $res->result();
}
return $res;
}
The error is in the foreach loop. I have printed the result and it shows the result in object array but when it goes to foreach loop. It show this error
"Call to a member function result() on a non-object "
But when I set db['default']['db_debug']=true , it shows that the $id is missing from the query whereas when it was false it was showing result in object array and giving error at loop. Any Help would be appreciated.Thanks
Controller Code
public function createInvoice( $id = "" )
{
if (empty($id))
{
$id = $this->input->post('dataid');
}
echo $id;
$data['jcc_line_list'] = $this->product_model->getJccLineItem($id,'array');
$data['jcc_line_lists'] = $this->product_model->getJccLineItem($id,'');
$data['items'] = $this->product_model->getAllSubInvoice($id);
$data['single_project'] = $this->product_model->getSingleProject($id);
$data['site'] = $this->product_model->getAllSiteArray();
$data['job_types'] = $this->product_model->getAllJobTypeArray();
$data['title'] = 'Invoice';
$data['operation'] = 'Create';
$data['buttonText'] = 'Save';
$data['id'] = $id;
$this->load->helper(array('form', 'url'));
$this->load->helper('security');
$this->form_validation->set_rules('line_item_id', 'Line Item', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('job_type_id', 'Job Type', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('site_id', 'Site', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('milestone', 'Milestone', 'required|xss_clean|max_length[50]');
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('error_message', validation_errors());
$this->load->view('admin/viewinvoicesub', $data);
} else if ($this->form_validation->run() == TRUE) {
$formData = array(
'invoice_id' => $id,
'line_item_id' => $this->form_validation->set_value('line_item_id'),
'job_type_id' => $this->form_validation->set_value('job_type_id'),
'site_id' => $this->form_validation->set_value('site_id'),
'milestone' => $this->form_validation->set_value('milestone'),
);
$this->product_model->insertInvoiceSub($formData);
$this->session->set_flashdata('sucess_message', "Data successfully save !");
redirect('Products/createInvoice', "refresh");
} else {
$this->load->view('admin/viewinvoicesub', $data);
}
}
Try this and let me know if that helps
public function getJccLineItem($id = '' ,$action = '')
{
if($id != '')
{
$res = array();
$q = 'SELECT * FROM jcc_line_items jli,ipo_line_item ili ,line_items li
WHERE jli.line_item_id= ili.id and li.id = jli.line_item_id
and ili.dn_number_id in ( Select dn_number from ipo where project_id= '.$id.')';
$res = $this->db->query($q)->result();
$jccLineItemArray = array();
if($action == 'array')
{
foreach($res as $key => $value) // The error comes in this line
{
$jccLineItemArray[ $value->id ] = $value->item_description;
}
$res = $jccLineItemArray;
}
return $res;
}
else
{
echo "id is null"; die();
}
}
And your Controller code should be
public function createInvoice( $id = "" )
{
$this->load->helper(array('form', 'url'));
$this->load->helper('security');
if ($id = "")
{
$id = (isset($this->input->post('dataid')))?$this->input->post('dataid'):3;// i am sure your error is from here
}
$data['jcc_line_list'] = $this->product_model->getJccLineItem($id,'array');
$data['jcc_line_lists'] = $this->product_model->getJccLineItem($id,'');
$data['items'] = $this->product_model->getAllSubInvoice($id);
$data['single_project'] = $this->product_model->getSingleProject($id);
$data['site'] = $this->product_model->getAllSiteArray();
$data['job_types'] = $this->product_model->getAllJobTypeArray();
$data['title'] = 'Invoice';
$data['operation'] = 'Create';
$data['buttonText'] = 'Save';
$data['id'] = $id;
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$this->form_validation->set_rules('line_item_id', 'Line Item', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('job_type_id', 'Job Type', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('site_id', 'Site', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('milestone', 'Milestone', 'required|xss_clean|max_length[50]');
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
if ($this->form_validation->run() === FALSE)
{
$this->session->set_flashdata('error_message', validation_errors());
$this->load->view('admin/viewinvoicesub', $data);
}
else
{
$formData = array(
'invoice_id' => $id,
'line_item_id' => $this->form_validation->set_value('line_item_id'),
'job_type_id' => $this->form_validation->set_value('job_type_id'),
'site_id' => $this->form_validation->set_value('site_id'),
'milestone' => $this->form_validation->set_value('milestone'),
);
$this->product_model->insertInvoiceSub($formData);
$this->session->set_flashdata('sucess_message', "Data successfully save !");
redirect('Products/createInvoice/'.$id, "refresh");
}
}
else
{
$this->load->view('admin/viewinvoicesub', $data);
}
}
Related
I can't update data in a record in CodeIgniter .
I have posted the code below:-
//CONTROLLER
//RESERVATION.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Reservation extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('reservation_model','reservation');
}
public function index()
{
$this->load->helper('url');
$this->load->view('manage_reservation');
}
public function reservationview()
{
$this->load->helper('url');
$this->load->view('view_reservation');
}
public function ajax_list()
{
$list = $this->reservation->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $reservation) {
$no++;
$row = array();
$row[] = $reservation->id;
$row[] = $reservation->dateReserved;
$row[] = $reservation->requestedBy;
$row[] = $reservation->facility;
$row[] = $reservation->dateFrom;
$row[] = $reservation->dateTo;
$row[] = $reservation->timeStart;
$row[] = $reservation->timeEnd;
$row[] = $reservation->status;
$row[] = $reservation->items;
$row[] = $reservation->purpose;
//add html for action
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="Edit" onclick="edit_reservation('."'".$reservation->id."'".')"><i class="glyphicon glyphicon-pencil"></i></a>
<a class="btn btn-sm btn-danger" href="javascript:void(0)" title="Hapus" onclick="delete_reservation('."'".$reservation->id."'".')"><i class="glyphicon glyphicon-trash"></i></a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->reservation->count_all(),
"recordsFiltered" => $this->reservation->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
public function ajax_edit($id)
{
$data = $this->reservation->get_by_id($id);
$data->dateFrom = ($data->dateFrom == '0000-00-00') ? '' : $data->dateFrom;
$data->dateTo = ($data->dateTo == '0000-00-00') ? '' : $data->dateTo; // if 0000-00-00 set tu empty for datepicker compatibility
echo json_encode($data);
}
public function ajax_add()
{
$this->_validate();
$data = array(
'id' => $this->input->post('id'),
'dateReserved' => $this->input->post('dateReserved'),
'requestedBy' => $this->input->post('requestedBy'),
'facility' => $this->input->post('facility'),
'dateFrom' => $this->input->post('dateFrom'),
'dateTo' => $this->input->post('dateTo'),
'timeStart' => $this->input->post('timeStart'),
'timeEnd' => $this->input->post('timeEnd'),
'status' => $this->input->post('status'),
'items' => $this->input->post('items'),
'purpose' => $this->input->post('purpose'),
);
$insert = $this->reservation->save($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_update()
{
$this->_validate();
$data = array(
'id' => $this->input->post('id'),
'dateReserved' => $this->input->post('dateReserved'),
'requestedBy' => $this->input->post('requestedBy'),
'facility' => $this->input->post('facility'),
'dateFrom' => $this->input->post('dateFrom'),
'dateTo' => $this->input->post('dateTo'),
'timeStart' => $this->input->post('timeStart'),
'timeEnd' => $this->input->post('timeEnd'),
'status' => $this->input->post('status'),
'items' => $this->input->post('items'),
'purpose' => $this->input->post('purpose'),
);
$this->reservation->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
public function ajax_delete($id)
{
$this->reservation->delete_by_id($id);
echo json_encode(array("status" => TRUE));
}
private function _validate()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('requestedBy') == '')
{
$data['inputerror'][] = 'requestedBy';
$data['error_string'][] = 'Requested Name is required*';
$data['status'] = FALSE;
}
if($this->input->post('dateFrom') == '')
{
$data['inputerror'][] = 'dateFrom';
$data['error_string'][] = 'Please Select a Date*';
$data['status'] = FALSE;
}
if($this->input->post('dateTo') == '')
{
$data['inputerror'][] = 'dateTo';
$data['error_string'][] = 'Please Select a Date*';
$data['status'] = FALSE;
}
if($this->input->post('timeStart') == '')
{
$data['inputerror'][] = 'timeStart';
$data['error_string'][] = 'Please select a Time*';
$data['status'] = FALSE;
}
if($this->input->post('timeEnd') == '')
{
$data['inputerror'][] = 'timeEnd';
$data['error_string'][] = 'Please select a Time*';
$data['status'] = FALSE;
}
if($this->input->post('status') == '')
{
$data['inputerror'][] = 'status';
$data['error_string'][] = 'Please Indicate Status*';
$data['status'] = FALSE;
}
if($this->input->post('items') == '')
{
$data['inputerror'][] = 'items';
$data['error_string'][] = 'Please select an Item*';
$data['status'] = FALSE;
}
if($this->input->post('purpose') == '')
{
$data['inputerror'][] = 'purpose';
$data['error_string'][] = 'Please indicate a Purpose*';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
}
//MODEL
//Reservation_model.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Reservation_model extends CI_Model {
var $table = 'tblreservation';
var $column_order = array('id','dateReserved','requestedBy','facility','dateFrom','dateTo','timeStart','timeEnd','status','items','purpose',null); //set column field database for datatable orderable
var $column_search = array('id','dateReserved','requestedBy','facility','dateFrom','dateTo','timeStart','timeEnd','status','items','purpose'); //set column field database for datatable searchable just firstname , lastname , address are searchable
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_search 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_search) - 1 == $i) //last loop
$this->db->group_end(); //close bracket
}
$i++;
}
if(isset($_POST['order'])) // here order processing
{
$this->db->order_by($this->column_order[$_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 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 = manage_reservation.php = save function
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('reservation/ajax_add')?>";
} else {
url = "<?php echo site_url('reservation/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
NEWBIE TO CODE IGNITER any help will be appreciated :)
try
public function update($where, $data){
$this->db->where($where);
$this->db->set($data); //array of new data
$this->db->update($this->table);
return $this->db->affected_rows();
}
Please print your query after the update statement, this will help you to know whether you query is correct or not.
$this->db->last_query();
Please check that query in model
Controller :
$update_id = array();
$update_id['id'] = $this->input->post('id');
$data = array(
'id' => $this->input->post('id'),
'dateReserved' => $this->input->post('dateReserved'),
'requestedBy' => $this->input->post('requestedBy'),
'facility' => $this->input->post('facility'),
'dateFrom' => $this->input->post('dateFrom'),
'dateTo' => $this->input->post('dateTo'),
'timeStart' => $this->input->post('timeStart'),
'timeEnd' => $this->input->post('timeEnd'),
'status' => $this->input->post('status'),
'items' => $this->input->post('items'),
'purpose' => $this->input->post('purpose'),
);
$result = $this->reservation->update('table_name',$update_id, $data);
Model :
$this->db->where($where);
$this->db->update($table, $data);
return $this->db->affected_rows();
I'm a total newbie to Wordpress and having a hard time figuring things out.
I'm using plugin called "WP-Pro-Quiz", a quiz plugin, and within the plugin there's an option to show "Leaderboard" of all users who completed the quiz. In the leaderboard on the frontend, there's user id, time, points and user's Display Name, etc for each user..
What I want to achieve is to make Display name clickable (and then to go to author's profile once clicked). That is, to connect Display Name with author profile who took the quiz, to create hyperlink from Display Name.
This is from controller WpProQuiz_Controller_Toplist.php :
<?php
class WpProQuiz_Controller_Toplist extends WpProQuiz_Controller_Controller
{
public function route()
{
$quizId = $_GET['id'];
$action = isset($_GET['action']) ? $_GET['action'] : 'show';
switch ($action) {
default:
$this->showAdminToplist($quizId);
break;
}
}
private function showAdminToplist($quizId)
{
if (!current_user_can('wpProQuiz_toplist_edit')) {
wp_die(__('You do not have sufficient permissions to access this page.'));
}
$view = new WpProQuiz_View_AdminToplist();
$quizMapper = new WpProQuiz_Model_QuizMapper();
$quiz = $quizMapper->fetch($quizId);
$view->quiz = $quiz;
$view->show();
}
public function getAddToplist(WpProQuiz_Model_Quiz $quiz)
{
$userId = get_current_user_id();
if (!$quiz->isToplistActivated()) {
return null;
}
$data = array(
'userId' => $userId,
'token' => wp_create_nonce('wpProQuiz_toplist'),
'canAdd' => $this->preCheck($quiz->getToplistDataAddPermissions(), $userId),
);
if ($quiz->isToplistDataCaptcha() && $userId == 0) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
$data['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL . '/' . $captcha->createImage();
$data['captcha']['code'] = $captcha->getPrefix();
}
}
return $data;
}
private function handleAddInToplist(WpProQuiz_Model_Quiz $quiz)
{
if (!wp_verify_nonce($this->_post['token'], 'wpProQuiz_toplist')) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
if (!isset($this->_post['points']) || !isset($this->_post['totalPoints'])) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$quizId = $quiz->getId();
$userId = get_current_user_id();
$points = (int)$this->_post['points'];
$totalPoints = (int)$this->_post['totalPoints'];
$name = !empty($this->_post['name']) ? trim($this->_post['name']) : '';
$email = !empty($this->_post['email']) ? trim($this->_post['email']) : '';
$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
$captchaAnswer = !empty($this->_post['captcha']) ? trim($this->_post['captcha']) : '';
$prefix = !empty($this->_post['prefix']) ? trim($this->_post['prefix']) : '';
$quizMapper = new WpProQuiz_Model_QuizMapper();
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
if ($quiz == null || $quiz->getId() == 0 || !$quiz->isToplistActivated()) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
if (!$this->preCheck($quiz->getToplistDataAddPermissions(), $userId)) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$numPoints = $quizMapper->sumQuestionPoints($quizId);
if ($totalPoints > $numPoints || $points > $numPoints) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$clearTime = null;
if ($quiz->isToplistDataAddMultiple()) {
$clearTime = $quiz->getToplistDataAddBlock() * 60;
}
if ($userId > 0) {
if ($toplistMapper->countUser($quizId, $userId, $clearTime)) {
return array('text' => __('You can not enter again.', 'wp-pro-quiz'), 'clear' => true);
}
$user = wp_get_current_user();
$email = $user->user_email;
$name = $user->display_name;
} else {
if ($toplistMapper->countFree($quizId, $name, $email, $ip, $clearTime)) {
return array('text' => __('You can not enter again.', 'wp-pro-quiz'), 'clear' => true);
}
if (empty($name) || empty($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
return array('text' => __('No name or e-mail entered.', 'wp-pro-quiz'), 'clear' => false);
}
if (strlen($name) > 15) {
return array('text' => __('Your name can not exceed 15 characters.', 'wp-pro-quiz'), 'clear' => false);
}
if ($quiz->isToplistDataCaptcha()) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
if (!$captcha->check($prefix, $captchaAnswer)) {
return array('text' => __('You entered wrong captcha code.', 'wp-pro-quiz'), 'clear' => false);
}
}
}
}
$toplist = new WpProQuiz_Model_Toplist();
$toplist->setQuizId($quizId)
->setUserId($userId)
->setDate(time())
->setName($name)
->setEmail($email)
->setPoints($points)
->setResult(round($points / $totalPoints * 100, 2))
->setIp($ip);
$toplistMapper->save($toplist);
return true;
}
private function preCheck($type, $userId)
{
switch ($type) {
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ALL:
return true;
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_ANONYM:
return $userId == 0;
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_USER:
return $userId > 0;
}
return false;
}
public static function ajaxAdminToplist($data)
{
if (!current_user_can('wpProQuiz_toplist_edit')) {
return json_encode(array());
}
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
$j = array('data' => array());
$limit = (int)$data['limit'];
$start = $limit * ($data['page'] - 1);
$isNav = isset($data['nav']);
$quizId = $data['quizId'];
if (isset($data['a'])) {
switch ($data['a']) {
case 'deleteAll':
$toplistMapper->delete($quizId);
break;
case 'delete':
if (!empty($data['toplistIds'])) {
$toplistMapper->delete($quizId, $data['toplistIds']);
}
break;
}
$start = 0;
$isNav = true;
}
$toplist = $toplistMapper->fetch($quizId, $limit, $data['sort'], $start);
foreach ($toplist as $tp) {
$j['data'][] = array(
'id' => $tp->getToplistId(),
'name' => $tp->getName(),
'email' => $tp->getEmail(),
'type' => $tp->getUserId() ? 'R' : 'UR',
'date' => WpProQuiz_Helper_Until::convertTime($tp->getDate(),
get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A')),
'points' => $tp->getPoints(),
'result' => $tp->getResult()
);
}
if ($isNav) {
$count = $toplistMapper->count($quizId);
$pages = ceil($count / $limit);
$j['nav'] = array(
'count' => $count,
'pages' => $pages ? $pages : 1
);
}
return json_encode($j);
}
public static function ajaxAddInToplist($data)
{
// workaround ...
$_POST = $_POST['data'];
$ctn = new WpProQuiz_Controller_Toplist();
$quizId = isset($data['quizId']) ? $data['quizId'] : 0;
$prefix = !empty($data['prefix']) ? trim($data['prefix']) : '';
$quizMapper = new WpProQuiz_Model_QuizMapper();
$quiz = $quizMapper->fetch($quizId);
$r = $ctn->handleAddInToplist($quiz);
if ($quiz->isToplistActivated() && $quiz->isToplistDataCaptcha() && get_current_user_id() == 0) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
$captcha->remove($prefix);
$captcha->cleanup();
if ($r !== true) {
$r['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL . '/' . $captcha->createImage();
$r['captcha']['code'] = $captcha->getPrefix();
}
}
}
if ($r === true) {
$r = array('text' => __('You signed up successfully.', 'wp-pro-quiz'), 'clear' => true);
}
return json_encode($r);
}
public static function ajaxShowFrontToplist($data)
{
// workaround ...
$_POST = $_POST['data'];
$quizIds = empty($data['quizIds']) ? array() : array_unique((array)$data['quizIds']);
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
$quizMapper = new WpProQuiz_Model_QuizMapper();
$j = array();
foreach ($quizIds as $quizId) {
$quiz = $quizMapper->fetch($quizId);
if ($quiz == null || $quiz->getId() == 0) {
continue;
}
$toplist = $toplistMapper->fetch($quizId, $quiz->getToplistDataShowLimit(), $quiz->getToplistDataSort());
foreach ($toplist as $tp) {
$j[$quizId][] = array(
'name' => $tp->getName(),
'date' => WpProQuiz_Helper_Until::convertTime($tp->getDate(),
get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A')),
'points' => $tp->getPoints(),
'result' => $tp->getResult()
);
}
}
return json_encode($j);
}
}
and from model WpProQuiz_Model_Toplist.php:
<?php
class WpProQuiz_Model_Toplist extends WpProQuiz_Model_Model
{
protected $_toplistId;
protected $_quizId;
protected $_userId;
protected $_date;
protected $_name;
protected $_email;
protected $_points;
protected $_result;
protected $_ip;
public function setToplistId($_toplistId)
{
$this->_toplistId = (int)$_toplistId;
return $this;
}
public function getToplistId()
{
return $this->_toplistId;
}
public function setQuizId($_quizId)
{
$this->_quizId = (int)$_quizId;
return $this;
}
public function getQuizId()
{
return $this->_quizId;
}
public function setUserId($_userId)
{
$this->_userId = (int)$_userId;
return $this;
}
public function getUserId()
{
return $this->_userId;
}
public function setDate($_date)
{
$this->_date = (int)$_date;
return $this;
}
public function getDate()
{
return $this->_date;
}
public function setName($_name)
{
$this->_name = (string)$_name;
return $this;
}
public function getName()
{
return $this->_name;
}
public function setEmail($_email)
{
$this->_email = (string)$_email;
return $this;
}
public function getEmail()
{
return $this->_email;
}
public function setPoints($_points)
{
$this->_points = (int)$_points;
return $this;
}
public function getPoints()
{
return $this->_points;
}
public function setResult($_result)
{
$this->_result = (float)$_result;
return $this;
}
public function getResult()
{
return $this->_result;
}
public function setIp($_ip)
{
$this->_ip = (string)$_ip;
return $this;
}
public function getIp()
{
return $this->_ip;
}
}
Fatal Error: call to a member function uploadFile() on a non-object
Getting this error of upload file function on Uploading File to dropbox using PHP API On live Server. Same Code Working fine on localhost and doing it in codeigniter. start of code is**
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
error_reporting(1);
require_once(APPPATH . 'libraries/dropbox/vendor/autoload.php');
use \Dropbox as dbx;
class Knowledge extends CI_Controller
{
public $appInfoFile;
public $requestPath; **
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
$this->load->helper('url');
$this->load->database();
$this->load->library('form_validation');
//load the models
$this->load->model('knowledge_model');
//$this->load->helper('messages');
//$this->load->model('messages_model');
$this->load->model('messages_model', 'send_messages');
// custom library in codeigniter
$this->appInfoFile = APPPATH.'libraries/dropbox/app-info.json';
$redirect_uri ='https://www.domainname.com/knowledge/add/';
$requestPath = $this->init();
session_start();
validate_user();
}
public function index($msg = NULL)
{
$session_data = $this->session->all_userdata();
$data['msg'] = $msg;
if (isset($session_data["validated"]) && $session_data["validated"] == '1') {
$data['title'] = 'Knowledge Center';
$data['records'] = $this->knowledge_model->get_all_rec();
// echo "<pre>".print_r($data['records'],true)."</pre>";exit;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('knowledge', $data);
$this->load->view('includes/footer');
} else {
redirect(base_url());
}
}
public function tag($msg = NULL)
{
$tagname = $this->uri->segment("3");
$tagnamehits = $this->uri->segment("4");
$session_data = $this->session->all_userdata();
$data['msg'] = $msg;
if (isset($session_data["validated"]) && $session_data["validated"] == '1') {
$data['title'] = 'Knowledge Center';
$data['update_rec'] = $this->knowledge_model->update_hits($tagnamehits);
$data['records'] = $this->knowledge_model->get_notifyrec_bytags($tagname);
//echo "<pre>".print_r($data['records'],true)."</pre>";exit;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('knowledge', $data);
$this->load->view('includes/footer');
} else {
redirect(base_url());
}
}
public function add()
{
//validate form input
$this->form_validation->set_rules('subject', 'subject', 'required');
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$seralizedtags = serialize($this->input->post('tagsar'));
//echo "<pre>".print_r($seralizedArray,true)."</pre>";exit;
// drop box upload filess
if (isset($_FILES['attached_file']['name']) && !empty($_FILES['attached_file']['name'])) {
$file_name= $_FILES['attached_file']['name'];
$return_result=$this->upload_to_dropbox($file_name);
$rev=$return_result['rev'];
$mime_type=$return_result['mime_type'];
$path=$return_result['path'];
$size=$return_result['size'];
$revision=$return_result['revision'];
}
if ($this->form_validation->run() == true) {
$session_data = $this->session->all_userdata();
$user_id = $session_data["userid"];
$data = array(
'user_id' => $user_id,
'edit_by_userid' => $user_id,
'subject' => $this->input->post('subject'),
'tags' => $seralizedtags,
'description' => $this->input->post('description'),
'dropbox_rev'=>$rev,
'dropbox_mim_type'=>$mime_type,
'dropbox_path'=>$path,
'dropbox_filesize'=>$size,
'dropbox_revision'=>$revision,
);
$message=$this->input->post('subject');
//for slack call
if(isset($message)){
$message=$message;
$messageType = "Knowledge_center";
$this->send_messages->send_message_on_slack($messageType);
}
//echo "<pre>" . print_r($data, true) . "</pre>";
$insert_res = $this->knowledge_model->insert_rec($data);
if ($insert_res != "conf") {
if ($insert_res == "subject") {
$this->session->set_flashdata('message', "<p>Subject Name already exist.Please change Subject</p>");
} else {
$this->session->set_flashdata('message', "<p>Error in Insertion.</p>");
}
echo '<script>window.location.href = "' . base_url() . 'knowledge/add";</script>';
} else {
$this->session->set_flashdata('message', "<p>Record added successfully.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
}
} else {
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$this->data['subject'] = array(
'name' => 'subject',
'class' => 'form-control round-input',
'id' => 'subject',
'placeholder' => 'Subject',
'type' => 'text',
'autofocus' => 'true',
'data-required' => '1',
'value' => $this->form_validation->set_value('subject'),
);
$this->data['tagdata'] = array(
'name' => 'tagsar',
'class' => 'form-control tags tags-input',
'id' => 'tagsar',
'type' => 'text',
'autofocus' => 'true',
'data-type' => 'tags',
'value' => $this->form_validation->set_value('tagsar'),
);
$data['desc'] = $this->form_validation->set_value('description');
// $data['dropbox']=$this->dropbox->dp();
$msg = "";
$data['title'] = 'Knowledge Center';
$data['msg'] = $msg;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('add_knowledge', $this->data);
$this->load->view('includes/footer');
}
}
public function view($id)
{
$update_rec = $this->knowledge_model->get_rec_byid($id);
$data['dropbox_detail']=array(
"dropbox_rev"=> $update_rec[0]->dropbox_rev,
"dropbox_mim_type"=> $update_rec[0]->dropbox_mim_type,
"dropbox_path"=> $update_rec[0]->dropbox_path,
"dropbox_filesize"=> $update_rec[0]->dropbox_filesize,
"dropbox_revision"=> $update_rec[0]->dropbox_revision,
);
$data['subject_data'] = $update_rec[0]->subject;
$data['tags_data'] = unserialize($update_rec[0]->tags);
$data['desc'] = $update_rec[0]->description;
$data['title'] = 'Knowledge Center';
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('view_knowledge', $this->data);
$this->load->view('includes/footer');
}
public function manage_notify()
{
$notifyid = $_POST["elid"];
$notifytext = $_POST["notifytext"];
$notify_rec = $this->knowledge_model->get_notifyrec_byid($notifytext);
$ret_res = "<ul>";
foreach ($notify_rec as $notify_record) {
$ret_res .= "<li>" . $notify_record->subject . "</li>";
}
$ret_res .= "</ul>";
echo $ret_res;
exit;
}
public function update($id)
{
//validate form input
$this->form_validation->set_rules('subject', 'subject', 'required');
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$update_rec = $this->knowledge_model->get_rec_byid($id);
//echo "<pre>".print_r($update_rec[0],true)."</pre>";exit;
$seralizedtags = serialize($this->input->post('tagsar'));
if ($this->form_validation->run() == true) {
$session_data = $this->session->all_userdata();
$user_id = $session_data["userid"];
$data = array(
'edit_by_userid' => $user_id,
'subject' => $this->input->post('subject'),
'tags' => $seralizedtags,
'description' => $this->input->post('description')
);
$recid = $this->input->post('recid');
// echo "<pre>".print_r($data,true)."</pre>";exit;
$update_res = $this->knowledge_model->update_rec($recid, $data);
if ($update_res > 0) {
$this->session->set_flashdata('message', "<p>Record Updated successfully.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
} else {
$this->session->set_flashdata('message', "<p>Error in Updation.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge/update/' . $recid . '";</script>';
}
} else {
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
if (isset($update_rec)) {
$this->data['recid'] = array(
'name' => 'recid',
'class' => 'form-control',
'id' => 'recid',
'type' => 'hidden',
'autofocus' => 'true',
'data-required' => '1',
'value' => $update_rec[0]->id,
);
$this->data['subject'] = array(
'name' => 'subject',
'class' => 'form-control round-input',
'id' => 'subject',
'placeholder' => 'Subject',
'type' => 'text',
'autofocus' => 'true',
'data-required' => '1',
'value' => $update_rec[0]->subject,
);
$tags_data = unserialize($update_rec[0]->tags);
$this->data['tagdata'] = array(
'name' => 'tagsar',
'class' => 'form-control tags tags-input',
'id' => 'tagsar',
'type' => 'text',
'autofocus' => 'true',
'data-type' => 'tags',
'value' => $tags_data,
);
$data['desc'] = $update_rec[0]->description;
} else {
$this->session->set_flashdata('message', "<p>Update Record not found.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
}
$msg = "";
$data['title'] = 'Knowledge Center';
$data['msg'] = $msg;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('edit_knowledge', $this->data);
$this->load->view('includes/footer');
}
}
public function download_dbx_file(){
$file_path = $_POST['dropbox_path'];
$mime_type = $_POST['dropbox_mim_type'];
$this->download_file($file_path,$mime_type);
}
public function del($id)
{
$this->knowledge_model->del_rec($id);
$this->session->set_flashdata('message', "<p>Record Deleted successfully.</p>");
redirect(base_url() . 'knowledge');
}
// for upload to dropbox //
function getAppConfig()
{
global $appInfoFile;
try {
$appInfo = dbx\AppInfo::loadFromJsonFile($this->appInfoFile);
}
catch (dbx\AppInfoLoadException $ex) {
throw new Exception("Unable to load \"$this->appInfoFile\": " . $ex->getMessage());
}
$clientIdentifier = "examples-web-file-browser";
$userLocale = null;
return array($appInfo, $clientIdentifier, $userLocale);
}
function getClient()
{
if (!isset($_SESSION['access-token'])) {
return false;
}
list($appInfo, $clientIdentifier, $userLocale) = $this->getAppConfig();
$accessToken = $_SESSION['access-token'];
return new dbx\Client($accessToken, $clientIdentifier, $userLocale,$appInfo->getHost());
}
function getWebAuth()
{
list($appInfo, $clientIdentifier, $userLocale) = $this->getAppConfig();
$redirectUri = getUrl("dropbox-auth-finish");
$csrfTokenStore = new dbx\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token');
return new dbx\WebAuth($appInfo, $clientIdentifier, $redirectUri, $csrfTokenStore, $userLocale);
}
function respondWithError($code, $title, $body = "")
{
$proto = $_SERVER['SERVER_PROTOCOL'];
header("$proto $code $title", true, $code);
echo renderHtmlPage($title, $body);
}
function getUrl($relative_path)
{
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
$scheme = "https";
} else {
$scheme = "http";
}
$host = $_SERVER['HTTP_HOST'];
$path = getPath($relative_path);
return $scheme."://".$host.$path;
}
function getPath($relative_path)
{
if (PHP_SAPI === 'cli-server') {
return "/".$relative_path;
} else {
return $_SERVER["SCRIPT_NAME"]."/".$relative_path;
}
}
function init()
{
global $argv;
// If we were run as a command-line script, launch the PHP built-in web server.
if (PHP_SAPI === 'cli') {
launchBuiltInWebServer($argv);
assert(false);
}
if (PHP_SAPI === 'cli-server') {
// For when we're running under PHP's built-in web server, do the routing here.
return $_SERVER['SCRIPT_NAME'];
}
else {
// For when we're running under CGI or mod_php.
if (isset($_SERVER['PATH_INFO'])) {
return $_SERVER['PATH_INFO'];
} else {
return "/";
}
}
}
function launchBuiltInWebServer($argv)
{
// The built-in web server is only available in PHP 5.4+.
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
fprintf(STDERR,
"Unable to run example. The version of PHP you used to run this script (".PHP_VERSION.")\n".
"doesn't have a built-in web server. You need PHP 5.4 or newer.\n".
"\n".
"You can still run this example if you have a web server that supports PHP 5.3.\n".
"Copy the Dropbox PHP SDK into your web server's document path and access it there.\n");
exit(2);
}
$php_file = $argv[0];
if (count($argv) === 1) {
$port = 5000;
} else if (count($argv) === 2) {
$port = intval($argv[1]);
} else {
fprintf(STDERR,
"Too many arguments.\n".
"Usage: php $argv[0] [server-port]\n");
exit(1);
}
$host = "localhost:$port";
$cmd = escapeshellarg(PHP_BINARY)." -S ".$host." ".escapeshellarg($php_file);
$descriptors = array(
0 => array("pipe", "r"), // Process' stdin. We'll just close this right away.
1 => STDOUT, // Relay process' stdout to ours.
2 => STDERR, // Relay process' stderr to ours.
);
$proc = proc_open($cmd, $descriptors, $pipes);
if ($proc === false) {
fprintf(STDERR,
"Unable to launch PHP's built-in web server. Used command:\n".
" $cmd\n");
exit(2);
}
fclose($pipes[0]); // Close the process' stdin.
$exitCode = proc_close($proc); // Wait for process to exit.
exit($exitCode);
}
public function upload_to_dropbox($filename){
if($filename != ''){
try {
$dbxClient = $this->getClient();
$remoteDir = "/";
if (isset($_POST['folder'])) $remoteDir = $_POST['folder'];
$remotePath = rtrim($remoteDir, "/")."/".$filename;
$fp = fopen($_FILES['attached_file']['tmp_name'], "rb");
$result = $dbxClient->uploadFile($remotePath, dbx\WriteMode::add(), $fp);
fclose($fp);
//$str = print_r($result, true);
return $result;
} catch (Exception $e) {
echo $e->getMessage();
exit;
}
}
else{
echo "File does not exists";
exit;
}
}
public function download_file($file_path,$file_mime_type){
if($file_path != '' && $file_mime_type != '' ) {
try {
$dbxClient = $this->getClient();
$path = $file_path;
$fd = tmpfile();
$metadata = $dbxClient->getFile($path, $fd);
header("Content-Type: $metadata[mime_type]");
fseek($fd, 0);
fpassthru($fd);
fclose($fd);
} catch (Exception $e) {
echo $e->getMessage();
exit;
}
}
else{
echo "Invalid Request";
exit;
}
}
}
i get the desired value for first var_dump but get a null value for both the var_dump on submitting the form. can anybody help me with this?
to be precise,i am able to get the desired result for get->trail->id when the form is not submitted,but once i complete the form,and submit it,the value of $id is assigned to be null.
public function trail_cat_cost($trail_unique_code = null)
{
if($this->userlib->isLoggedIn())
{
$code = $trail_unique_code;
$user_id = $this->userlib->getId();
$id = $this->seller_store_model->get_trail_id($code, $user_id);
var_dump($id);
$choice = $this->input->post("travel_cat");
if(is_null($choice))
{
$choice = array();
}
$travel_cat = implode(',', $choice);
$choice1 = $this->input->post("travel_subcat");
if(is_null($choice1))
{
$choice1 = array();
}
$travel_subcat = implode(',', $choice1);
$trail_currency = $this->input->post('trail_currency');
$trail_cost = $this->input->post('trail_cost');
$cost_valid_from = $this->input->post('cost_valid_from');
$cost_valid_upto = $this->input->post('cost_valid_upto');
//$this->form_validation->set_rules('travel_cat', 'Travel Category', 'trim|required');
//$this->form_validation->set_rules('travel_subcat', 'Travel Subcategory', 'trim|required');
$this->form_validation->set_rules('trail_currency', 'Trail Currency', 'trim|required');
$this->form_validation->set_rules('trail_cost', 'Trail Cost', 'trim|required');
$this->form_validation->set_rules('cost_valid_from', 'Cost Valid From', 'trim|required');
$this->form_validation->set_rules('cost_valid_upto', 'Cost Valid Upto', 'trim|required');
if($this->form_validation->run() == FALSE)
{
$this->load->view('trail_cat_cost');
}
else
{
var_dump($id);
$this->seller_store_model->trail_cat_cost($user_id, $id, $travel_cat, $travel_subcat, $trail_currency, $trail_cost, $cost_valid_from, $cost_valid_upto);
echo "success";
//redirect('/seller_store/trail_overview/'.$date);
}
}
else
{
echo "User not authorised";
}
}
Model Code From Comment
public function get_trail_id($code, $user_id) {
$query = $this->db->query("SELECT id FROM trail_basic_info WHERE trail_unique_code = '$code' AND user_id = '$user_id'"); foreach($query->result() as $row) { $id = $row->id; $data = array('trail_id'=>$id); $this->db->update($this->search, $data, array('trail_unique_code'=>$code, 'user_id'=>$user_id)); return $row->id;
}
I am having trouble and since more than a week trying to find a solution to disallow duplicate form content if it is already exists in database.
So it will check all rows excluding the id (row) what currently I am editing and if same value exists it should give error message.
Here is my Code.
Position Controller
public function position_edit($id = NULL)
{
$this->data['title'] = '<i class="fa fa-user"></i> ' . lang('position_edit');
$this->data['position'] = $this->positions_model->get($id);
count($this->data['position']) || $this->data['errors'][] = 'position could not be found';
$id = $this->uri->segment(4);
$this->db->where('position', $this->input->post('position'));
!$id || $this->db->where('id !=', $id);
$pos = $this->positions_model->get();
echo '<pre>', print_r($pos), '</pre>';
if (count($pos) > 0) {
$this->form_validation->set_rules('position', 'lang:position_code', 'trim|required|max_length[10]|is_unique[positions.position]|xss_clean');
$this->form_validation->set_message('is_unique', lang('error_position_exists'));
}
if ($this->form_validation->run() === TRUE) {
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);
$this->session->set_flashdata('message', lang('position_record_updated'));
$this->data['message'] = $this->session->flashdata('message');
$this->session->set_flashdata('message_type', 'success');
$this->data['message_type'] = $this->session->flashdata('message_type');
//redirect('admin/hr/positions', 'refresh');
}
// Load the view
$this->load->view('hr/positions/edit', $this->data);
}
Position Model
class Positions_Model extends MY_Model
{
protected $_table_name = 'positions';
protected $_order_by = 'label ASC';
// This $rules currently not in use since it has been
// set directly to the controller edit method code
public $rules = array(
'position' => array(
'field' => 'position',
'label' => 'Position Code',
'rules' => 'trim|required|max_length[10]|xss_clean'
),
'label' => array(
'field' => 'label',
'label' => 'Position Label',
'rules' => 'trim|required|max_length[50]|xss_clean'
),
);
public function get_new()
{
$position = new stdClass();
$position->position = '';
$position->label = '';
return $position;
}
public function get_positions($id = NULL, $single = FALSE)
{
$this->db->get($this->_table_name);
return parent::get($id, $single);
}
public function get_positions_array($id = NULL, $single = FALSE)
{
$this->db->get($this->_table_name);
$positions = parent::get($id, $single);
$array = array();
foreach($positions as $pos){
$array[] = get_object_vars($pos);
}
return $array;
}
public function delete($id)
{
// Delete a position
parent::delete($id);
}
}
DB Model
class MY_Model extends CI_Model
{
protected $_table_name = '';
protected $_primary_key = 'id';
protected $_primary_filter = 'intval';
protected $_order_by = '';
public $rules = array();
protected $_timestamps = FALSE;
function __construct()
{
parent::__construct();
}
public function array_from_post($fields)
{
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
public function get($id = NULL, $single = FALSE)
{
if($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
} elseif($single == TRUE) {
$method = 'row';
} else {
$method = 'result';
}
if(!count($this->db->ar_orderby)) {
$this->db->Order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
public function get_by($where, $single = FALSE)
{
$this->db->where($where);
return $this->get(NULL, $single);
}
public function save($data, $id = NULL)
{
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
} else {
// Update
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
public function delete($id)
{
$filter = $this->_primary_filter;
$id = $filter($id);
if (!$id) {
return FALSE;
}
$this->db->where($this->_primary_key, $id);
$this->db->limit(1);
$this->db->delete($this->_table_name);
}
}
I have tried callback function also but it is not working at all and couldn't find what causing the issue.
EDIT:
Please note it The above code is giving message if I am inserting the value which already exists but it is not validating and storing the data if the row is not exists
Updated
if ($this->form_validation->run() === TRUE) {
//print_r($this->positions_model->unique_value('position', $this->uri->segment(4)));
if($this->positions_model->unique_value('position', $this->uri->segment(4))) {
$this->form_validation->set_message('unique_value', lang('error_position_exists'));
} else {
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);
$this->session->set_flashdata('message', lang('position_record_updated'));
$this->data['message'] = $this->session->flashdata('message');
$this->session->set_flashdata('message_type', 'success');
$this->data['message_type'] = $this->session->flashdata('message_type');
redirect('admin/hr/positions', 'refresh');
}
}
In Controller
public function unique_value($field, $id)
{
$id = $this->uri->segment(4);
$this->db->where($field, $this->input->post($field));
!$id || $this->db->where('id !=', $id);
$position = $this->positions_model->get();
if (count($position)) {
return TRUE;
}
return FALSE;
}
Please Note: I don't know what exactly happens to your code, but I wouldn't check between insert or update into the model, just in the controller
I would solve it using a checkExist Model function, that would check if all the values you want to check exists into the DDBB, and work according to it. I would also do it in the controller instead of the model. First, you validate the fields, and then you check if values exists excluding the edit id:
$values_from_post = $this->positions_model->array_from_post(array('position', 'label'));
// $editId is to avoid the id of the row you were editing
if ($this->form_validation->run() === TRUE ) {
if ( !$this->positions_model->check_duplicate( $values_from_post, $editId ) ) ){
// Insert Value
} else {
// Update Value
}
And in your model, you check the duplicate via a where if the values exists:
public function check_duplicate( $values_from_post, $editId ) {
foreach ( $values_from_post as $key => $value ) {
$this->db->where( $key, $value );
}
$this->db->where('id !=', $editId );
$result = $this->db->get($this->_table_name);
return ( ( $result->num_rows > 0 ) ? true : false );
}
Please, I didn't check the code, but that is the idea, instead of doing it in the model, control it in the controller and then insert or update depending of what happens.
Here is the default validation rule of CodeIgniter for checking the duplicate entries in two columns.
$this->form_validation->set_rules('form_field_name','Title here','required|max_length[255]|unique[table.table_column1,table.table_column2]');