Codeigniter: Can I pass an array to $ci->db->select()? - php

I'm new to CodeIgniter, and trying to find the best way to pass variable parameters to $ci->db->select()
Sometimes I need one field back, sometimes I need 3, but I'd like one function for this. Here's my get function:
function db_get($table, $what, $where) {
$this->db->where($where);
if( $what ) {
$this->db->select($what);
}
return $this->db->get($table)->row_array();
}
Can I call it like:
$table = 'table_name';
$what = array('field_1', 'field_2');
$where = array('field_3' => 'value');
$result = $ci->import_db->db_get($table, $what, $where);
Or do I need to implode it first? like:
$what = implode(",", $what);

Related

Larvavel Model and Parameters not found error

I'm very new to PHP and Laravel, I'm getting an eror that I can't make head or tail of.
public function filtered($col, $sort = null, $search = null, $ordering='desc')
{
$field = $this->table . '.' . $col ;
Log::info('BaseModel::filtered->' . $field) ;
$data = $this;
// check if search variable not empty
if ($search != null)
{
$data = $data->where(function ($query) use ($search){
return $query->where($field,'like','%'.$search.'%') ;
});
// check if sort variable not empty
if ($sort != null)
{
$sorts = explode('|', $sort);
$data = $data->orderBy($sorts[0],$sorts[1]);
}
}
...
The code above is giving the error: Undefined variable: field. From the Log output I get this:
[2017-06-21 06:32:25] local.INFO: BaseModel::filtered->organisation.name
I've tried calling the field variable by $this->field as well, also fails. I also get the same error if i reference the $col parameter directly. Yet both $search and $sort are fine.
$data = $data->where(function ($query) use ($search, $field) { //Add extra parameters inside your use same as search.
return $query->where($field,'like','%'.$search.'%') ;
});

Write update query in php to update set of rows - Zend framework

I use the following code:
$str= array('createdid' => $creator_newid);
$where = array();
$where['id IN'] = $instance_ids;
$this->_table->update($str, $where);
And here the $instance_ids contains set of string (that is 1, 2, 3, 4, 5, 6…) and I'm getting zend error.
How do I solve this?
Use Zend_Db_Abstract methods like
public function updatestatus($updateAry,$id) {
if(!empty($id)) {
try{
$res = $this->getDbTable()->update($updateAry, array('user_id=?'=>$id));
if (false === $res) {
return 0; // bool false returned, query failed
} else {
return 1;
}
} catch (Zend_Exception $zex){}
}
}
here
$updateAry is the data you want to update.
array('user_id=?'=>$id) It is like were clause
Use the Zend_Db_Adapter methods
$str = array('createdid' => $creator_newid);
$where = array(
$this->_table->getAdapter()->quoteInto('id IN(?)', $instance_ids))
);
$this->_table->update($str, $where);
The adapter will carefully escape and quote params for you.

How to return mysqli result object from a function in a class?

So.. I am practicing my PHP by writing a database object with CRUD operations.. However, I am having trouble returning a result object from the database object.
This is the relevant "select_where" function which lives inside the db Class and takes one parameter specifying the table name:
function select_where(array $values, $table, $what = "*")
{
$where_stmt = '';
if(count($values)>0)
{
$fields = array_keys($values);
$vals = array_values($values);
if ($what != "*")
{
if(is_array($what)===TRUE)
{
$what = implode($what, ',');
}
else //assume string! -- needs better error handling!
{
//Don;t do anything for now
}
}
$where_stmt = "WHERE ";
for( $i=0 ; $i<count($fields) ; $i++)
{
$where_stmt .= "$field[$i] = '$vals[$i]' AND ";
}
$where_stmt .= "$field[$i] = '$vals[$i]'";
}//else: array is an empty one, meaning SELECT ALL;
$query = "SELECT $what FROM `$table` $where_stmt;";
;
if($result = $this->mysqli_conn->query($query))
{
echo "RESULT:<br />";
print_r($result);
return $result;
}else{
return false;
}
}
The print_r function prints the attributes of the result object with no issues.. BUT when I call my function, it does not.. As so:
$db = new db();
$result = $db->select_all('codes');
print_r($result);
print_r does not print anything...
I am 100% sure that this has to do with my lack of understanding of how PHP OOP works; while I look for answers elsewhere, any suggestions or solutions are highly appreciated!
LOOKS LIKE I've Found the answer:
ROOKIE MISTAKE!
In my code, I used the helper function
$result = $db->select_all('codes');
which actually looked like this:
function select_all($table, $what="*" )
{
$empty_array = array();
$this->select_where($empty_array, $table, $what);
}
But as one can see, there was no return from THIS function! So now:
function select_all($table, $what="*" )
{
$empty_array = array();
return $this->select_where($empty_array, $table, $what);
}
is the solution!
Thank you again

how to make group by optional in zend framework?

i have a fetchAll function in zend:
public function fetchAll($where = 1, $order = null, $limit = null, $group = null, array $fields = null)
{
$where = (null == $where) ? 1 : $where;
$fields = (!isset($fields)) ? '*' : $fields;
$select = $this->db->select()
->from("table", $fields)
->where($where)
->order($order)
->group($group)
->limit($limit, $offset);
echo $select; exit;
$result = $this->db->fetchAll($select);
return $this->getResultObjects($result);
}
and i can call this function $this->fetchAll('field = 1', null, 10);
i can $order to null and the query will work just fine but not the $group for some reason.
How can i make it so that the group is optional and goes in only if i sat it to something?
thanks
The methods are chained so you can split it up:
$select = $this->db->select()
->from("table", $fields)
->where($where);
->order($order)
->limit($limit, $offset);
if ($group) {
$select->group($group);
}
$result = $this->db->fetchAll($select);
return $this->getResultObjects($result);
Every method in the chain (from, where, order, etc) returns an instance of Zend_Db_Select. So every time you call one of those methods you can immediately follow it up with another method call from that same class.
These code blocks are identical:
// With chaining
$select = $this->db->select()
->from("table", $fields)
->where($where);
->order($order)
->limit($limit, $offset);
// No chaining
$select = $this->db->select();
$select = $select->from("table", $fields);
$select = $select->where($where);
$select = $select->order($order);
$select = $select->limit($limit, $offset);
You can see why chaining is preferred. Note: the assignment ($select =) is mostly superflous in the non-chain example, I only left it in to show the clunkyness.
You can do something like this:
$select = $this->db->select()
->from("table", $fields)
->where($where)
->order($order)
->limit($limit, $offset);
if(!empty($group)){
$select->group($group)
}
This works because doctrine won't execute your query into you call execute. So until then you can keep building the query.
Doh, I thought your question was regarding Doctrine. But yeah apparently it works in a similar fashion with ZendDb. See Mike B's answer.

How to pass an array into a function, and return the results with an array

So I'm trying to learn how to pass arrays through a function, so that I can get around PHP's inability to return multiple values. Haven't been able to get anything to work so far, but here is my best try. Can anybody point out where I'm going wrong?
function foo($array)
{
$array[3]=$array[0]+$array[1]+$array[2];
return $array;
}
$waffles[0]=1;
$waffles[1]=2;
$waffles[2]=3;
foo($waffles);
echo $waffles[3];
For clarification: I want to be able to pass multiple variables into a function, do something, then return multiple variables back out while keeping them seperate. This was just an example I was trying to get working as a work around for not being able to return multiple variables from an array
You seem to be looking for pass-by-reference, to do that make your function look this way (note the ampersand):
function foo(&$array)
{
$array[3]=$array[0]+$array[1]+$array[2];
}
Alternately, you can assign the return value of the function to a variable:
function foo($array)
{
$array[3]=$array[0]+$array[1]+$array[2];
return $array;
}
$waffles = foo($waffles)
You're passing the array into the function by copy. Only objects are passed by reference in PHP, and an array is not an object. Here's what you do (note the &)
function foo(&$arr) { # note the &
$arr[3] = $arr[0]+$arr[1]+$arr[2];
}
$waffles = array(1,2,3);
foo($waffles);
echo $waffles[3]; # prints 6
That aside, I'm not sure why you would do that particular operation like that. Why not just return the sum instead of assigning it to a new array element?
function foo(Array $array)
{
return $array;
}
Try
$waffles = foo($waffles);
Or pass the array by reference, like suggested in the other answers.
In addition, you can add new elements to an array without writing the index, e.g.
$waffles = array(1,2,3); // filling on initialization
or
$waffles = array();
$waffles[] = 1;
$waffles[] = 2;
$waffles[] = 3;
On a sidenote, if you want to sum all values in an array, use array_sum()
I always return multiple values by using a combination of list() and array()s:
function DecideStuffToReturn() {
$IsValid = true;
$AnswerToLife = 42;
// Build the return array.
return array($IsValid, $AnswerToLife);
}
// Part out the return array in to multiple variables.
list($IsValid, $AnswerToLife) = DecideStuffToReturn();
You can name them whatever you like. I chose to keep the function variables and the return variables the same for consistency but you can call them whatever you like.
See list() for more information.
i know a Class is a bit the overkill
class Foo
{
private $sum = NULL;
public function __construct($array)
{
$this->sum[] = $array;
return $this;
}
public function getSum()
{
$sum = $this->sum;
for($i=0;$i<count($sum);$i++)
{
// get the last array index
$res[$i] = $sum[$i] + $sum[count($sum)-$i];
}
return $res;
}
}
$fo = new Foo($myarray)->getSum();
Here is how I do it. This way I can actually get a function to simulate returning multiple values;
function foo($array)
{
foreach($array as $_key => $_value)
{
$str .= "{$_key}=".$_value.'&';
}
return $str = substr($str, 0, -1);
}
/* Set the variables to pass to function, in an Array */
$waffles['variable1'] = "value1";
$waffles['variable2'] = "value2";
$waffles['variable3'] = "value3";
/* Call Function */
parse_str( foo( $waffles ));
/* Function returns multiple variable/value pairs */
echo $variable1 ."<br>";
echo $variable2 ."<br>";
echo $variable3 ."<br>";
Especially usefull if you want, for example all fields in a database
to be returned as variables, named the same as the database table fields.
See 'db_fields( )' function below.
For example, if you have a query
select login, password, email from members_table where id = $id
Function returns multiple variables:
$login, $password and $email
Here is the function:
function db_fields($field, $filter, $filter_by, $table = 'members_table') {
/*
This function will return as variable names, all fields that you request,
and the field values assigned to the variables as variable values.
$filter_by = TABLE FIELD TO FILTER RESULTS BY
$filter = VALUE TO FILTER BY
$table = TABLE TO RUN QUERY AGAINST
Returns single string value or ARRAY, based on whether user requests single
field or multiple fields.
We return all fields as variable names. If multiple rows
are returned, check is_array($return_field); If > 0, it contains multiple rows.
In that case, simply run parse_str($return_value) for each Array Item.
*/
$field = ($field == "*") ? "*,*" : $field;
$fields = explode(",",$field);
$assoc_array = ( count($fields) > 0 ) ? 1 : 0;
if (!$assoc_array) {
$result = mysql_fetch_assoc(mysql_query("select $field from $table where $filter_by = '$filter'"));
return ${$field} = $result[$field];
}
else
{
$query = mysql_query("select $field from $table where $filter_by = '$filter'");
while ($row = mysql_fetch_assoc($query)) {
foreach($row as $_key => $_value) {
$str .= "{$_key}=".$_value.'&';
}
return $str = substr($str, 0, -1);
}
}
}
Below is a sample call to function. So, If we need to get User Data for say $user_id = 12345, from the members table with fields ID, LOGIN, PASSWORD, EMAIL:
$filter = $user_id;
$filter_by = "ID";
$table_name = "members_table"
parse_str(db_fields('LOGIN, PASSWORD, EMAIL', $filter, $filter_by, $table_name));
/* This will return the following variables: */
echo $LOGIN ."<br>";
echo $PASSWORD ."<br>";
echo $EMAIL ."<br>";
We could also call like this:
parse_str(db_fields('*', $filter, $filter_by, $table_name));
The above call would return all fields as variable names.
You are not able to return 'multiple values' in PHP. You can return a single value, which might be an array.
function foo($test1, $test2, $test3)
{
return array($test1, $test2, $test3);
}
$test1 = "1";
$test2 = "2";
$test3 = "3";
$arr = foo($test1, $test2, $test3);
$test1 = $arr[0];
$test2 = $arr[1];
$test3 = $arr[2];
Another way is:
$NAME = "John";
$EMAIL = "John#gmail.com";
$USERNAME = "John123";
$PASSWORD = "1234";
$array = Array ("$NAME","$EMAIL","$USERNAME","$PASSWORD");
function getAndReturn (Array $array){
return $array;
}
print_r(getAndReturn($array));

Categories