Unable to change value at edit time with codeIgniter validation - php

Here i have a list of categories and user can add a new category as well as edit them.
Now at the edit time i'm using server-side validation by codeigniter for reduce redundancies . but the issue is the, whenever i edit an existing category then it can't update it because it compare with their original value, that is wrong. i trying to many time but unable to fix this issue.
Here is my code
public function category_upd()
{
extract($_POST);
$userId = $this->session->userdata('id');
$original_value = $this->db->query("SELECT cat_name FROM category WHERE user_id=".$userId." and cat_name ='".$_POST['cat_name']."'") ;
$original_value = $original_value->result_array();
$original_value = $original_value[0]['cat_name'];
$original_value2 = $this->db->query("SELECT cat_name FROM category WHERE user_id=".$userId." and cat_name ='".$_POST['cat_name']."'") ;
$original_value2 = $original_value2->result_array();
$original_value2 = $original_value2[0]['cat_name'];
if(ucwords($_POST['cat_name']) != $original_value) {
$this->session->set_flashdata('cat_failed','Category must be unique.');
$is_unique = '|is_unique[category.cat_name]';
} else if(ucwords($original_value2 == "")){
echo "go";
exit;
$this->session->set_flashdata('cat_failed','Category must be unique.');
$is_unique = '|is_unique[category.cat_name]';
} else {
$is_unique = '';
}
$this->form_validation->set_rules('cat_name','Category','trim|required'.$is_unique);
if($this->form_validation->run() ) {
A snap with error
I need your kind efforts. Thanks

Set validation Rules like this and you need to pass category id value
$this->form_validation->set_rules('cat_name', 'cat_name', 'required|trim|edit_unique[category.category_name.' . $_POST['category_id'].'.'.$_POST['user_id']. ']', array('edit_unique' => 'Category must be unique.'));
And developed one function edit_unique on Form_validation.php like this
Filepath system/libraries/Form_validation.php
public function edit_unique($str, $field)
{
sscanf($field, '%[^.].%[^.].%[^.].%[^.]', $table, $field,$id, $field2);
return isset($this->CI->db)
? ($this->CI->db->limit(1)->get_where($table, array($field => $str, 'id !=' => $id,'user_id'=>$field2))->num_rows() === 0)
: FALSE;
}

Check category name is alredy in database.
$newcategoryName=$this->input->post('category');
$query = $this->db->get_where('category', array('cat_name' => $newcategoryName,'user_id' => $userId));
$val=$query->result_array();
$original_value = $val[0]['cat_name'];
if($newcategoryName != $original_value) {
$is_unique = '|is_unique[users.EMAIL]';
} else {
$is_unique = '';
}
$this->form_validation->set_rules('cat_name', 'Category', 'required|trim|xss_clean'.$is_unique);

Related

Join 3 tables codeigniter php

I have 3 tables guest_user_info,pg_company,user_profile.
In guest_user_info have 2 columns:
g_uid | company_id
In pg_company have 2 columns:
company_id | user_id
In user_profile have 2 columns:
id |user_email
Here i want to get user_email from user_profile.i have g_uid value (in guest_user_info table).i want company_id from guest_user_info and get the company_id and match with pg_company table,there i can get user_id.then match with that user_id with id in user_profile table.at last i need user_email from user_profile table
Well its a simple one, you just need to join using active query in CodeIgniter.
$this->db->select("UP.id", "UP.user_email");
$this->db->from("guest_user_info AS GU");
$this->db->join("pg_company AS PC", "PC.company_id=GU.company_id");
$this->db->join("user_profile AS UP", "UP.id=PC.user_id");
$this->db->where("GU.g_uid", $guid);
$query = $this->db->get();
return $query->result();
In above code, $guid you have to provide which you have.
Also please take a look at these links:
https://www.codeigniter.com/userguide3/database/query_builder.html
https://www.codeigniter.com/userguide2/database/active_record.html
You get so many things after reading this.
Check bellow code it`s working fine and common model function also
supported more then one join and also supported multiple where condition
order by ,limit.it`s EASY TO USE and REMOVE CODE REDUNDANCY.
================================================================
*Album.php
//put bellow code in your controller
=================================================================
$album_id='';//album id
//pass join table value in bellow format
$join_str[0]['table'] = 'pg_company';
$join_str[0]['join_table_id'] = 'pg_company.company_id';
$join_str[0]['from_table_id'] = 'guest_user_info.company_id';
$join_str[0]['join_type'] = '';//set join type
$join_str[1]['table'] = 'user_profile';
$join_str[1]['join_table_id'] = 'user_profile.id';
$join_str[1]['from_table_id'] = 'guest_user_info.user_id';
$join_str[1]['join_type'] = '';
$selected ="guest_user_info.*,user_profile.user_name,pg_company.name";
$condition_array=array('guest_user_info.g_uid' => $g_uid);
$albumData= $this->common->select_data_by_condition('guest_user_info', $condition _array, $selected, '', '', '', '', $join_str);
//call common model function
if (!empty($albumData)) {
print_r($albumData); // print album data
}
=========================================================================
Common.php
//put bellow code in your common model file
========================================================================
function select_data_by_condition($tablename, $condition_array = array(), $data = '*', $sortby = '', $orderby = '', $limit = '', $offset = '', $join_str = array()) {
$this->db->select($data);
//if join_str array is not empty then implement the join query
if (!empty($join_str)) {
foreach ($join_str as $join) {
if ($join['join_type'] == '') {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id']);
} else {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id'], $join['join_type']);
}
}
}
//condition array pass to where condition
$this->db->where($condition_array);
//Setting Limit for Paging
if ($limit != '' && $offset == 0) {
$this->db->limit($limit);
} else if ($limit != '' && $offset != 0) {
$this->db->limit($limit, $offset);
}
//order by query
if ($sortby != '' && $orderby != '') {
$this->db->order_by($sortby, $orderby);
}
$query = $this->db->get($tablename);
//if limit is empty then returns total count
if ($limit == '') {
$query->num_rows();
}
//if limit is not empty then return result array
return $query->result_array();
}

sort varchar column codeigniter

i first checked if there any same problems like mine i ddnt find anything.
all are sorting alphanumeric column mixed with numeric data.
here is my problem.
i have a table that contain column A datas like this.
WRG-01 WRG-39 WRG-22 WRG-45 WRG-43
need to sort that as
WRG-01 WRG-22 WRG-39 WRG-43 WRG-45
this is the code i using so far in codeigniter frame work
$data['products'] = $this->db->order_by('product_id', 'asc')->get('products');
in mysql i can use this query to get done my work
preg_replace("/[^\d]/", "",'product_id'), 'asc')
How to apply it to my above codeigniter code?
here is search funtion
public function search()
{
$data['title'] = 'Search Product';
$product_name = $this->input->get('product_name');
$product_id = $this->input->get('product_id');
$product_category = $this->input->get('product_category');
$secondCategory = $this->input->get('secondCategory');
$thirdCategory = $this->input->get('thirdCategory');
$data['category'] = $this->db->order_by('id', 'asc')->get_where('categories', ['parent' => 0]);
if($product_category != '')
{
$data['secondCategory'] = $this->db->get_where('categories', ['parent' => $product_category]);
}
if($secondCategory != '')
{
$data['thirdCategory'] = $this->db->get_where('categories', ['parent' => $secondCategory]);
}
if($product_name != '')
{
$this->db->like('product_name', $product_name);
}
if($product_id != '')
{
$this->db->where('product_id', $product_id);
}
if($product_category != '')
{
$this->db->where('product_category', $product_category);
}
if($secondCategory != '')
{
$this->db->where('secondCategory', $secondCategory);
}
if($thirdCategory != '')
{
$this->db->where('thirdCategory', $thirdCategory);
}
$data['products'] = $this->db->order_by('product_id' 'asc')->get('products');
theme('all_product', $data);
}
i can't use sql query here because products is result array from product table.
Use MySQL cast
cast(product_id as SIGNED)
or
cast(product_id as UNSIGNED)
Try query like that :-
select * from products cast(product_id as UNSIGNED) ASC|DESC
Try this
$query= $this->db->query("SELECT * FROM products WHERE ??==?? ORDER BY product_id ASC");
$result= $query->result_array();
return $result;
as default data will sort by Ascending Order
This is in model. So if you pass it to controller it will return data as Objective Array.
So in controller you can access
$result = $this->model_name->method_for_above_code();
$name = $result[0]['name'];
$id = $result[0]['id'];
if in View
$result['this_for_view'] = $this->model_name->method_for_above_code();
foreach ($this_for_view as $new_item) {
echo "Name is ".$new_item['name'];
echo "ID is ".$new_item['id'];
}

PDO Update 1 column multiple rows with array

I am struggling to workout a good method to update one column of my wcx_options table.
The new data is sent fine to the controller but my function isn't working at all.
I assumed i could loop through each column by option_id updating with the values from the array.
The database:
I update the option_value column with the new information via a jQuery AJAX Call to a controller which then calls a function from the backend class.
So far i have the following code:
if(isset($_POST['selector'])) {
if($_POST['selector'] == 'general') {
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token'])
&& $_POST['token'] === $_SESSION['token']){
$site_name = $_POST['sitename'];
$site_url = $_POST['siteurl'];
$site_logo = $_POST['sitelogo'];
$site_tagline = $_POST['sitetagline'];
$site_description = $_POST['sitedescription'];
$site_admin = $_POST['siteadmin'];
$admin_email = $_POST['adminemail'];
$contact_info = $_POST['contactinfo'];
$site_disclaimer = $_POST['sitedisclaimer'];
$TimeZone = $_POST['TimeZone'];
$options = array($site_name, $site_url, $site_logo, $site_tagline, $site_description, $site_admin, $admin_email,$contact_info, $site_disclaimer, $TimeZone);
// Send the new data as an array to the update function
$backend->updateGeneralSettings($options);
}
else {
$_SESSION['status'] = '<div class="error">There was a Problem Updating the General Settings</div>';
}
}
}
This is what i have so far in terms of a function (It doesnt work):
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$where = array('option_id' => $i);
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$where'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
With the given DB-layout i'd suggest to organize your data as assiciative array using the db fieldnames, like:
$option = array(
'site_name' => $_POST['sitename'],
'site_url' => $_POST['siteurl'],
// etc.
'timeZone' => $_POST['TimeZone']
);
And than use the keys in your query:
public function updateGeneralSettings($options) {
foreach($options as $key => $value) {
$this->queryIt("UPDATE wcx_options SET option_value='$value' WHERE option_name='$key'");
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
}
(However, are you sure, you do not want to have all options together in one row?)
Change your query, you try to use an array as where condition. In the syntax you used that won't work. Just use the counter as where condition instead of define a $where variable. Try this:
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$i'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}

Laravel Query Builder: where condition based on user input

Here is my output of print_r($_POST)
array([id] => '123', [name] => '', [place] => '', [color] => '')
Where name , place and color are optional fields submitted by user..... user may select only name, place or color, name + color, color + place, or all three name + color + place.
How can I put where condition for these options chosen by user? Let's say for example, In Laravel we select DB table using the following statement...
$Select_db = Db::table('mytable')
->where('name', Input::get('name'))
->where('place', Input::get('place'))
->where('color', Input::get('color'))
->select()
->get();
As you can see above condition works only if there is an input for all fields from user, based on user input I want add where condition, how do we fix this???
Note: In this particular scenario, I am aware I could use isset() for each condition. However, what if there are many optional inputs?
Try this:-
$Select_db = DB::table('mytable');
if (Input::get('name') != "")
$Select_db->where('name', Input::get('name'));
if (Input::get('place') != "")
$Select_db->where('place', Input::get('place'));
if (Input::get('color') != "")
$Select_db->where('color', Input::get('color'));
$result = $Select_db->get();
And if there are multiple columns to match, then try using this:-
$Select_db = DB::table('mytable');
foreach($_POST as $key => $val){
if(Input::get($key) != ""){
$Select_db->where($key, Input::get($key));
}
}
$Select_db->get();
what about
$Select_db = Db::table('mytable');
foreach($_POST as $key => $val) {
$Select_db->where($key, Input::get($key));
}
$Select_db->query()->get();
maybe consider to copy your $_POST and remove undesired values before you enter foreach:
unset($postcopy['badvar'])
public function filter(Request $request)
{
$first_name = $request->input('first_name');
$sur_name = $request->input('sur_name');
$email_work = $request->input('email_work');
$country = $request->input('country');
$position = $request->input('position');
$event_id = $request->input('event_id');
$event_name = $request->input('event_name');
$nature_of_business = $request->input('nature_of_business');
$mobile_number = $request->input('mobile_number');
$event_date = $request->input('event_date');
$record = DB::table('exceldatas');
if ($request->has('first_name')){
$record->where('first_name', $first_name);
}
if ($request->has('sur_name')) {
$record->where('sur_name', $sur_name);
}
if ($request->has('email_work')) {
$record->where('email_work', $email_work);
}
if ($request->has('country')) {
$record->where('country', $country);
}
if ($request->has('event_name')) {
$record->where('event_name', $event_name);
}
if ($request->has('nature_of_business')) {
$record->where('nature_of_business', $nature_of_business);
}
if ($request->has('mobile_number')) {
$record->where('mobile_number', $mobile_number);
}
if ($request->has('event_date')) {
$record->where('event_date', $event_date);
}
$record =$record->paginate(15);
return view('showresult')->with('record', $record);
}

Codeigniter DataGrid Class

So, I am building myself a simple(ish) datagrid class for my CodeIgniter app.
What I am wondering is, I have some columns that I would like to "format" in that I mean, some may contain only a 1 or a 0, yet I want to turn them into a Yes or No respectively.
How can I do this? In other words, I want to be able to pass in another parameter..something like:
$this->_columnCallBack pass it an array like array(column_number=>'NameOfCallBackFunction')
I am assuming that I would do it somewhat like I did the _columnclass, where I pass in the column number, and the class as an array... but I don't know how I would get the function to fire off to do the replacement...
Code
class O7thDG {
public function __construct($params){
$this->_table = $params['table'];
$this->_pk = $params['pk'];
$this->_fields = (isset($params['fields'])) ? $params['fields'] : null;
$this->_where = (isset($params['where'])) ? $params['where'] : null;
$this->_order = (isset($params['order'])) ? $params['order'] : null;
$this->_extras = (isset($params['extras'])) ? $params['extras'] : null;
$this->_add = (isset($params['add'])) ? $params['add'] : FALSE;
$this->_edit = (isset($params['edit'])) ? $params['edit'] : FALSE;
$this->_delete = (isset($params['delete'])) ? $params['delete'] : FALSE;
$this->_editlink = (isset($params['editlink'])) ? $params['editlink'] : null;
$this->_deletelink = (isset($params['deletelink'])) ? $params['deletelink'] : null;
$this->_editlinkextras = (isset($params['editlinkextras'])) ? $params['editlinkextras'] : null;
$this->_deletelinkextras = (isset($params['deletelinkextras'])) ? $params['deletelinkextras'] : null;
$this->_tableid = (isset($params['tableid'])) ? $params['tableid'] : null;
$this->_tableclass = (isset($params['tableclass'])) ? $params['tableclass'] : null;
$this->_columnclass = (isset($params['columnclass'])) ? $params['columnclass'] : null;
$this->_includeheader = (isset($params['includeheader'])) ? $params['includeheader'] : TRUE;
$this->_allowpaging = (isset($params['allowpaging'])) ? $params['allowpaging'] : FALSE;
$this->_sorting = (isset($params['sorting'])) ? $params['sorting'] : null;
$this->_columncallback = (isset($params['columncallback'])) ? $params['columncallback'] : null;
}
public function BuildIt($responsive = TRUE){
$_ci =& get_instance();
$_ci->load->database();
$_ci->load->library('table');
$_ci->load->library('TKCommon', null, 'comm');
$fldlist = $this->_buildSelectFieldList();
$_ci->db->select($fldlist);
$cols = $this->_buildColumnFieldList();
$ret = '';
if($this->_where != null){
// build the where
}
if($this->_order != null){
// build the order
}
if($this->_extras != null){
// build the extras
}
// Query the specified table
$qry = $_ci->db->get($this->_table);
if($cols == null){
$cols = $_ci->db->list_fields($this->_table);
$fldlist = $cols;
}else{
$fldlist = explode(', ', $fldlist);
}
if($qry){
// throw the results into an associative array
$rs = $qry->result_array();
if($rs){
$rCt = count($rs);
$cCt = $qry->num_fields();
// add our responsive wrapper
if($responsive){
$ret .= '<div class="table-responsive">';
}
// fire up our table
$tid = '';
$tc = '';
if($this->_tableid != null){$tid = ' id="' .$this->_tableid . '"';}
if($this->_tableclass != null){$tc = ' class="' .$this->_tableclass . '"';}
$_ci->table->set_template(array('table_open'=>'<table' . $tid . $tc . '>'));
// build our header row, but only if we need to
if($this->_includeheader && $cCt > 0){
// see if we need to include the admin column
if($this->_edit || $this->_delete){
$_ci->table->set_heading(array_merge($cols, array('Admin')));
}else{
$_ci->table->set_heading($cols);
}
}
// build each records row
for($r = 0; $r < $rCt; ++$r){
$ca = array();
for($c = 0; $c < $cCt; ++$c){
if(($this->_columnclass != null) && ($c == key($this->_columnclass))){
// figure out which column needs the class, and what class needs to be applied
$ca[] = $this->_columnCallback($c, array('data'=>$rs[$r][$fldlist[$c]], 'class'=>$this->_columnclass[key($this->_columnclass)]));
}else{
$ca[] = $this->_columnCallback($c, $rs[$r][$fldlist[$c]]);
}
}
// see if we need to include the admin column
if(($this->_edit || $this->_delete) && ($this->_editlink != null || $this->_deletelink != null)){
$txt = '';
if($this->_edit &&($this->_editlink != null)){
$txt .= '<span class="fa fa-pencil fa-lg"></span> ';
}
if($this->_delete &&($this->_deletelink != null)){
$txt .= '<span class="fa fa-trash-o fa-lg"></span>';
}
if(($this->_columnclass != null) && ($cCt == key($this->_columnclass))){
$ca[] = array('data'=>$txt, 'class'=>$this->_columnclass[key($this->_columnclass)]);
}else{
$ca[] = $txt;
}
}
$_ci->table->add_row($ca);
}
$ret .= $_ci->table->generate();
// close our responsive wrapper
if($responsive){
$ret .= '</div>';
}
}else{
$ret .= $_ci->comm->ErrorBox('There was an issue running the query, please make sure at least your primary key, and table are correct.');
}
}else{
$ret .= $_ci->comm->ErrorBox('There was an issue running the query, please make sure at least your primary key, and table are correct.');
}
return $ret;
}
// build our select's field list
private function _buildSelectFieldList(){
if($this->_fields == null){
return '*';
}else{
$flds = array_map(function($item){return $item['field'];}, $this->_fields);
return implode(', ', $flds);
}
}
// build our tables column list
private function _buildColumnFieldList(){
if($this->_fields == null){
return null;
}else{
return array_map(function($item){return $item['label'];}, $this->_fields);
}
}
private function _columnCallback($col, $val){
if($this->_columncallback != null){
if($col == key($this->_columncallback))
return $this->_columncallback[key($this->_columncallback)]($val);
}else{
return $val;
}
}
}
and my external function that I may want to use is simply:
// Format boolean value to Yes or No
public function YesNo($val){
return ((bool)$val) ? 'Yes' : 'No' ;
}
CI Documentation for the table class has $this->table->function, however, the function(s) passed applies to the entire table
What about using and/or anonymous functions:
http://docs.php.net/manual/es/function.func-get-args.php
http://php.net/manual/en/functions.anonymous.php
Update 2 "reloaded"
You could also check grocery crud, it's CI library and do some interesting things that can be useful for you project:
http://www.grocerycrud.com/
Grocery crud uses call_user_func from PHP and allows you to use any function declaread in your controller, if this is what you need then it's just matter of time and check grocery crud code.
In the library a protected property is declared for each callback for example (line #3386 v1.4.1):
/* Callbacks */
protected $callback_before_insert = null;
So you/me/any can set the callback function in case is needed, then check for any callback setted doing something like (line #878 GroceryCrud 1.4.1):
if($this->callback_before_insert !== null)
{
$callback_return = call_user_func($this->callback_before_insert, $post_data);
if(!empty($callback_return) && is_array($callback_return))
$post_data = $callback_return;
elseif($callback_return === false)
return false;
}
Of course there's a method to set the callback (line #4518 from v1.4.1):
public function callback_before_insert($callback = null)
{
$this->callback_before_insert = $callback;
return $this;
}
And the user/dev set the callback doing:
$crud->callback_before_insert(array($this,'my_callback'));
And/Or this technique allows you use something like:
$this->load->model('Customers');
$crud->callback_before_insert(array($this->Customers,'getCustomersCallback'));
even if you're usign php 5.3 or greater you can use an anonymous method:
$crud->callback_before_insert(function($post_array){
$post_array['user_id'] = $this->session->userdata('user_id');
return $post_array;
});
More info: http://www.grocerycrud.com/documentation/tutorial_using_callbacks
About Grocery Crud:
Author: John Skoumbourdis (more about author/library)
Web: GroceryCrud
License: released with dual licensing, using the GPL v3 and the MIT license.
Update 3
Update I've read more carefully your question, thinking functions varible can work for you:
http://php.net/manual/es/functions.variable-functions.php
See the first and second samples here: http://www.php.net/manual/en/language.oop5.php
Still don't know if they will work "outside" your class, but it could.
These functions will work as you want to, but you need to rewrite a bit for your needs.
function callback1($array, $row_id, $function)
{
if(function_exists($function))
return $function($array[$row_id]);
else
return 0;
}
function YesNo($val)
{
return intval($val) ? 'Yes' : 'No' ;
}
#example of array and usage of script.
$array = array('id' => '0', 'id2' => '1');
$ok = callback1($array, 'id2', 'YesNo');
Make filters array
$this->filters = ['column_name' => 'function_name', 'column_name2' => 'otherFunction'];
Then you just apply the filter to the data
if ( array_key_exists($column_name, $this->filters) ) {
// Add row that contains filtered data
$row_data = $this->filters[$column_name]($column_val);
}else{
$row_data = $column_val;
}
If your functions aren't available globally (not in a helper or built-in php), you'll have to use something like this:
call_user_func(array($this, $this->filters[$column_name]), $column_val);
OR
$this->{$this->filters[$column_name]}($column_val);
This would run a function from inside the library O7...

Categories