I would like know if it is possible to merge sql queries like the following from codeigniters active record.
//get assigned contacts
$this->db->select('*, CONCAT(first_name, " " ,last_name) AS name', FALSE);
$this->db->from('customers_contacts');
$this->db->join('customers_accounts', 'customers_accounts.contact_id = customers_contacts.contact_id');
$this->db->like('CONCAT(first_name, " " ,last_name)', $q);
$results1 = $this->db->get();
//get non assigned contacts
$this->db->select('*, CONCAT(first_name, " " ,last_name) AS name', FALSE);
$this->db->from('customers_contacts');
$this->db->like('CONCAT(first_name, " " ,last_name)', $q);
$results2 = $this->db->get();
I tried using $query = array_merge($results1, $results2); but that does not work, I believe because ->get() is returning an array of objects.
So I got it to work by putting both through a foreach loop, and then merging the resulting arrays. But I need to do some conditionals that would be easier in one foreach loop than two.
You can use like below
$arr_results1 = $this->db->get()->result_array();
$arr_results2 = $this->db->get()->result_array();
var_dump(array_merge($arr_results1,$arr_results2));
Hope this will help you!
After a bit of reading I came up with the following and it works!
//first query here...
$results1 = $this->db->get()->result_array();
//second query here...
$results1 = $this->db->get()->result_array();
//then...
$query = array_merge($results1,$results2);
You must always do $results->result(); to get an array of rows after $results = $this->db->get();. note: $results->result(); is an array of objects.
For example
# ...
$results1 = $this->db->get();
# ...
$results2 = $this->db->get();
$results = array();
if ($results1->num_rows())
{
$results = array_merge($results, $results1->result());
}
if ($results2->num_rows())
{
$results = array_merge($results, $results2->result());
}
return $results;
This will return an array of objects (rows) and you iterate through data as usual:
foreach ($results as $row)
{
echo $row->id;
echo $row->column_name_1;
# and so on...
}
Related
I want to select only $limit records from the table with the category $cat.
foreach($cats as $cat) {
$query = $this->createQuery();
$query->matching($query->equals('type', $cat));
$query->setLimit((int)$limit);
$result[] = $query->execute();
}
Is it possible to combine the query result so one query result?
I think your query is something like ,
"SELECT * FROM table_name WHERE type IN ('".$cats."')"
Here $cats is an array of categories like,
$cats = array("cat1", "cat2", "cat3");
Then the extabse query will be,
$query = $this->createQuery();
$query->matching($query->in('type', $cats));
$query->setLimit((int)$limit);
$result = $query->execute();
In the above query in() checks if a single-valued property exists in a multi-value operand.
For more details refer : http://docs.typo3.org/typo3cms/ExtbaseFluidBook/6-Persistence/3-implement-individual-database-queries.html
Thank you, I found another way that worked for me:
public function findAllLimitedByCategory($limit, $category){
$cats = explode(",",$category);
$result = array();
foreach($cats as $cat) {
$query = $this->createQuery();
$query->matching($query->equals('type', $cat));
$query->setLimit((int)$limit);
$result[] = $query->execute()->toArray();
}
$out = array();
foreach($result as $r)
$out = array_merge($out, $r);
return $out;
}
...but I have to sort the array by php with this solution
I have this code i need to use to get results from a database, I'm on codeigniter. This is how the query looks like,
$this->db->select('*');
$this->db->where('broadcast_id', $bid);
$query = $this->db->get('ih_noticeboard');
$result = $query->result();
if($query->num_rows() < 1){
$data = "no feed ";
}else{
$data = $result;
}
the $bid in the where clause is got from this code,
$this->db->select('broadcast_id');
$this->db->where('broadcast_subscribers', $id);
$query = $this->db->get('ih_broadcastors ');
if($query->num_rows() < 1){
$data = "user not subscribed to any broadcasting";
}else{
$ress = $query->result();
foreach ($ress as $row){
$bid = $row->broadcast_id;
}`
Now the select uses only one $bid, how can I use the $bid as an array?
It's quite simple .
just use $this->db->where_in('broadcast_id', $bid);
instead if $this->db->where('broadcast_id', $bid);
https://ellislab.com/codeigniter/user-guide/database/active_record.html#select
Wouldn't it be better to have one query to get the feeds?
$this->db->select("ih_noticeboard.*");
$this->db->from("ih_noticeboard");
$this->db->join("ih_broadcastors", "ih_noticeboard.broadcast_id = ih_broadcasters.broadcast_id");
$this->db->where("ih_broadcastors.broadcast_subscribers", $id);
$result->db->get()->result();
Assuming you want to select in the table where
name='jane' and broadcast_id=2 #as an example
$bid=array(
'name'=>'jane',
'broadcast_id'=>'2'
)
$this->db->where($bid);
$this->db->from($table_name);
$query = $this->db->get()->result_array();
return $query;
Please notice that the $bid as array must be formated to suite the next database table to be queried. You can do this using foreach loop E.g
foreach ($ress as $row){
$bid = array(
'name'=>$row['name'],
'broadcast_id'=>$row['id']
);
}
I believe I am using the PDO fetch functions completely wrong. Here is what I am trying to do:
Query a row, get the results, use a helper function to process the results into an array.
Query
function userName($db){
$q = $db->prepare("SELECT id, name FROM users WHERE id = :user");
$q->bindParam(":user", $user);
$q->execute();
$qr = $q->fetchAll(PDO::FETCH_ASSOC);
if ($qr->rowCount() > 0){
foreach($qr as $row){
$names[$row['id']] = buildArray($row);
}
return $names;
}
}
My custom array building function
function buildArray($row){
$usernames = array();
if(isset($row['id'])) $usernames['id'] = $row['id'];
if(isset($row['name'])) $usernames['name'] = $row['name'];
}
I'm actually getting exactly what I want from this, but when I echo inbetween I see that things are looping 3 times instead of once. I think I am misusing fetchAll.
Any help appreciated
If you're going to build a new array, there's not much point in having fetchAll() build an array. Write your own fetch() loop:
function userName($db){
$q = $db->prepare("SELECT id, name FROM users WHERE id = :user");
$q->bindParam(":user", $user);
$q->execute();
$names = array();
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
$names[$row['id']] = $row;
}
return $names;
}
There's also no need for buildArray(), since $row is already the associative array you want.
In past Codeigniter projects, I have always used $query->result_array() instead of $query->result()
For example, as an array, I would have the following in a model:
$this->db->select('id, username');
$this->db->from('users');
$query = $this->db->get();
$result = array();
foreach ($query->result_array() as $row)
{
$id = $row['id'];
$result[$id]['id'] = $row['id'];
$result[$id]['username'] = strtolower($row['username']);
)
return $result;
It can get really messy with more records and I have to add all of the fields even if I just need to perform operations on only one of them.
Now, for my current project, I am trying to just $query->result(), which is just an array of objects, but I'm not sure how to perform operations on them and return the results.
For example, if I'm using $query->result() and I want to make every username lowercase (strtolower), how would I perform those changes in the model?
The answer to your example and comment:
$results = $query->result();
foreach($results as $result){
$result->username = strtolower($result->username);
}
return $results;
foreach($query->result() as $row){
$username_lower = strtolower($row->username);
//if you want to actually update the record in the db
$this->db->where('id',$row->id);
$this->db->update('users', array('username' => $row->username));
}
I have a custom html page which posts to php variables which then fills out custom sql queries.
function load_table($db, $old_table, $startRow, $nameColumn, $ipColumn, $addressColumn, $cityColumn, $stateColumn, $zipColumn, $countryColumn)
{
$select = "SELECT $nameColumn, $ipColumn, $addressColumn, $cityColumn, $stateColumn, $zipColumn, $countryColumn FROM " .$old_table.";";
$q = mysqli_query($db, $select);
return $q;
}
It works perfectly when all the variables are holding a value, but I need a way to dynamically assert this query, so that if the user is missing a column, i.e zip code is not in their table, it will still run without ruining the query.
$array = array();
if ($nameColumn)
$array[] = $nameColumn;
if ($ipColumn)
$array[] = $ipColumn;
// etc...
$cols = implode(',', $array);
if ($cols)
{
$select = "SELECT $cols FROM $old_table;";
$q = mysqli_query($db, $select);
return $q;
}
Or you can use
$select = "SELECT ".(($nameColumn != '')?$nameColumn.",":"")." .......";
See also: http://br2.php.net/manual/en/function.func-get-args.php
Put all your variables in an array then do the following:
function load_table($db, $old_table, $startRow, array $columns) {
$columns = array_filter($columns, 'strlen'); // removes empty values
$select = "SELECT " . implode(",", $columns) . " FROM " .$old_table.";";
$q = mysqli_query($db, $select);
return $q;
}
You can give it a default:
function load_table($db, $old_table, $startRow, $nameColumn="Default name", $ipColumn, $addressColumn, $cityColumn, $stateColumn, $zipColumn, $countryColumn)
In this case $nameColumn will always have a value unless otherwise specified