I am coming from CF to PHP, specifically Laravel, so I apologize for such a basic question.
I have a function in a controller :
public function search(
$surveyId = 0
, $sampleId = 0
, $data = []
, $dataSeg = 0
, $returnLimit = 1000
, $returnStartRow = 1
, $sortOn = ""
, $sortDir = ""
, $previousData = []
){
// bunch of code
}
I am wondering if it is possible to pass in only specific variables that are needed like I can in cf? Trying to do something like this :
$myData = [
"State" => "AZ"
];
$allRecords = (new MyController)->search($surveyId=3762,$data=$myData,$sortOn="name");
I know this is a simple process in cf if the only three variable I need for a specific call are, in this case, the surveyId and the data array and the sortOn but I can't find the correct way to do this in Laravel (php) or even if this is a possibility at all. BTW I am using Laravel 5.7
RESULT :
Based on #Nguyen's answer here is what the beginning of my controller ended up looking like, incase it is helpful to someone else :
public function search($params){
// parameters that should be passed in
$surveyId = key_exists("surveyId", $params) ? $params['surveyId'] : 0;
$sampleId = key_exists("sampleId", $params) ? $params['sampleId'] : 0;
$data = key_exists("data", $params) ? $params['data'] : [];
$dataSeg = key_exists("dataSeg", $params) ? $params['dataSeg'] : 0;
$returnLimit = key_exists("returnLimit", $params) ? $params['returnLimit'] : 1000;
$returnStartRow = key_exists("returnStartRow", $params) ? $params['returnStartRow'] : 1;
$sortOn = key_exists("sortOn", $params) ? $params['sortOn'] : "";
$sortDir = key_exists("sortDir", $params) ? $params['sortDir'] : "";
$previousData = key_exists("previousData", $params) ? $params['previousData'] : [];
// end parameters that should be passed in
## logic code
}
You can't pass parameter by name. If you want, change parameter to array like this:
public function search($param){
// your code here
}
$allRecords = (new MyController)->search(["surveyId"=>3762,"data"=>$myData,"sortOn"=>"name"]);
Related
I am trying to update records(first_name,last_name) from MySQL using Codeigniter
but if I do not update first_name OR last_name then record become empty from MySQL,
I want existing record should not be removed/deleted,how can I do this? here is my code
$add_data['user_id'] = ($this->input->post('user_id') && !empty($this->input->post('user_id'))) ? $this->input->post('user_id') : NULL;
$add_data['first_name'] = ($this->input->post('first_name') && !empty($this->input->post('first_name'))) ? $this->input->post('first_name') : NULL;
$add_data['last_name'] = ($this->input->post('last_name') && !empty($this->input->post('last_name'))) ? $this->input->post('last_name') : NULL;
$data = array(
'first_name'=>$add_data['first_name'],
'last_name'=>$add_data['last_name'],
);
$this->db->where('id',$add_data['user_id']);
$query=$this->db->update('users', $data);
Here is snippet:
$saveArr = [];
if(!empty($this->input->post('first_name')){
$saveArr['first_name'] = $this->input->post('first_name');
}
if(!empty($this->input->post('last_name')){
$saveArr['last_name'] = $this->input->post('last_name');
}
$this->db->where('id',$add_data['user_id']);
$query=$this->db->update('users', $saveArr);
Hope this will help you :)
I am working with rest API in CodeIgniter
I am working with update API so I want to update only those columns/fields which I sent via postman,
for example, if I sent only first_name and last_name then only these columns should be updated not all columns,
but current code updating all columns, Here is my code where I am wrong?
public function update_userrecords()
{
$add_data['user_id'] = ($this->input->post('user_id') && !empty($this->input->post('user_id'))) ? $this->input->post('user_id') : NULL;
$add_data['first_name'] = ($this->input->post('first_name') && !empty($this->input->post('first_name'))) ? $this->input->post('first_name') : NULL;
$add_data['last_name'] = ($this->input->post('last_name') && !empty($this->input->post('last_name'))) ? $this->input->post('last_name') : NULL;
$add_data['password'] = ($this->input->post('password') && !empty($this->input->post('password'))) ? $this->input->post('password') : NULL;
$t=time();
$data = array(
'first_name'=>$add_data['first_name'],
'last_name'=>$add_data['last_name'],
'password'=>md5($add_data['password']),
'updated_on'=>$t,
);
$this->db->where('id',$add_data['user_id']);
$this->db->update('users', $data);
}
You can use this way
Set you input field in new array and update that array. I have added one field in $insert_data. you can add as much you want.
public function update_userrecords()
{
$add_data['user_id'] = ($this->input->post('user_id') && !empty($this->input->post('user_id'))) ? $this->input->post('user_id') : NULL;
$insert_data = [];
if($this->input->post('first_name') && !empty($this->input->post('first_name'))) {
$insert_data['first_name'] = $this->input->post('user_id');
}
$t=time();
$this->db->where('id',$add_data['user_id']);
$this->db->update('users', $insert_data);
}
I am trying to include Elastic search into my application. In a scenario a user can select field type and enter the searchable value.
Let say, Search using First Name and Value is 'ABC'.
I have tried this using bool query,but How i can use 'more_like_this' query method?.
This what I have done so far.
$searchParams['index'] = 'articles';
$searchParams['type'] = 'article';
$searchParams['body']['query']['match']['body'] = 'ABC';
$queryResponse = $es->search($searchParams);
but if i put more_like_this into the query field,data cannot be selected.
any help please?
Thanks in advance
This is the edited code
$searchParams['index'] = 'articles';
$searchParams['type'] = 'article';
$searchParams['body']['query']['more_like_this']['fields'] = array('body','title');
$searchParams['body']['query']['more_like_this']['like_text'] = $q;
$searchParams['body']['query']['more_like_this']['min_term_freq'] = 1;
$searchParams['body']['query']['more_like_this']['percent_terms_to_match'] = 1;
$searchParams['body']['query']['more_like_this']['min_doc_freq'] = 1;
Can you tell me what this lines for?
$searchParams['body']['query']['more_like_this']['min_term_freq'] = 1;
$searchParams['body']['query']['more_like_this']['percent_terms_to_match'] = 1;
$searchParams['body']['query']['more_like_this']['min_doc_freq'] = 1;
You need to do an array, that will look like a json to ES:
{
"query": {
"more_like_this": {
"fields": [
"text"
],
"like_text": "apple",
"min_term_freq": 1,
"percent_terms_to_match": 1,
"min_doc_freq": 1
}
}
}
So in PHP it will be:
$searchParams['body']['query']['more_like_this']['fields'] = array('body');
$searchParams['body']['query']['more_like_this']['like_text'] = 'apple';
$searchParams['body']['query']['more_like_this']['min_term_freq'] = 1;
$searchParams['body']['query']['more_like_this']['percent_terms_to_match'] = 1;
$searchParams['body']['query']['more_like_this']['min_doc_freq'] = 1;
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...
I want my search to focus on variables in the URL string. Currently it uses a form based search.
It uses this
<?php
include('db.php'); // include your code to connect to DB.
$tbl_name="mobile"; //your table name
$whereClauses = array();
if (! empty($_POST['Model'])) $whereClauses[] ="model='".mysql_real_escape_string($_POST['Model'])."'";
if (! empty($_POST['Mins'])) $whereClauses[] ="minutes='".mysql_real_escape_string($_POST['Mins'])."'";
if (! empty($_POST['Texts'])) $whereClauses[] ="texts='".mysql_real_escape_string($_POST['Texts'])."'";
if (! empty($_POST['Freegifts'])) $whereClauses[] ="free_gift='".mysql_real_escape_string($_POST['Freegifts'])."'";
if (! empty($_POST['Network'])) $whereClauses[] ="network_name='".mysql_real_escape_string($_POST['Network'])."'";
if (! empty($_POST['Merchant'])) $whereClauses[] ="merchant_category='".mysql_real_escape_string($_POST['Merchant'])."'";
$where = '';
if (count($whereClauses) > 0) { $where = ' WHERE '.implode(' AND ',$whereClauses); }
$sql = mysql_query("SELECT * FROM $tbl_name".$where);
?>
However, I have added this to my page:
<?php
$model = $_GET['model']; //gets model from URL
$mins = $_GET['mins']; //gets mins from URL
$texts = $_GET['texts']; //gets mins from URL
$freegift = $_GET['free-gift']; //gets mins from URL
$network = $_GET['network']; //gets mins from URL
$plan = $_GET['plan']; //gets mins from URL
?>
It needs to be so not all variables are required. Any help would be appreciated.
Thanks in advance :)
There are a number of options that will return value or NULL:
<?php
$model = (isset($_GET['model']) ? $_GET['model'] : NULL);
$mins = (isset($_GET['mins']) ? $_GET['mins'] : NULL);
$texts = (isset($_GET['texts']) ? $_GET['texts'] : NULL);
$freegift = (isset($_GET['free-gift']) ? $_GET['free-gift'] : NULL);
$network = (isset($_GET['network']) ? $_GET['network'] : NULL);
$plan = (isset($_GET['plan']) ? $_GET['plan'] : NULL);
?>
This will get the variables from their correponding $_GET element, only if there is one set.
Alternative syntax (shorter):
<?php
$model = ($_GET['model'] ? $_GET['model'] : NULL);
$mins = ($_GET['mins'] ? $_GET['mins'] : NULL);
$texts = ($_GET['texts'] ? $_GET['texts'] : NULL);
$freegift = ($_GET['free-gift'] ? $_GET['free-gift'] : NULL);
$network = ($_GET['network'] ? $_GET['network'] : NULL);
$plan = ($_GET['plan'] ? $_GET['plan'] : NULL);
?>
Alternative (untested though):
<?php
$vars = array('model','mins','texts','free-gift','network','plan');
foreach($vars as $value) {
$$value = (isset($_GET[$value]) ? $_GET[$value] : NULL);
}
?>
EDIT:
In order to set a WHERE clause based on it, I suggest:
<?php
$vars = array('model','mins','texts','free-gift','network','plan');
foreach($vars as $value) {
$$value = (isset($_GET[$value]) ? $_GET[$value] : NULL);
unset $vars[$value]; //sweeping the NULL ones
}
$where_clause = $vars[0]; //the only remaining value after previous cleanup
?>