how to query in codeigniter database - php

$this->db->select('*');
$where = "(rank = '2')";
$this->db->where($where);
$this->db->from('deceased');
$this->db->join('causes', 'causes.id = deceased.id');
i have a query from codeigniter, and i should get the rank 2, but the problem is, if there is no rank 2 i should get the rank 1.
db_deceased (id primary key)
id date_died
1 2014-01-01
2 2014-03-19
db_causes (id foreign key)
id cause rank
1 J96.0 1
1 J44.1 2
2 I21 1

Probably you should try with $this->db->or_where(); either $this->db->or_where_in(); but also consider documentation's approach writing arguments there. Your $where variable should be like $where = array('name =' => '2');
$this->db->select('*');
$this->db->where('name =', '2');
$this->db->or_where('name =', '1');
$this->db->from('deceased');
$this->db->join('causes', 'causes.id = deceased.id');
Active records are pretty well explained in documentation.

Related

Laravel Query how to check if column starts with 0

I have a CRUD application with a Registration table and a Category table. In the RegistrationController, I use a query with Category, so I have made another query. I struggled with checking if every other gender_id has a cte_from that starts with 0. The cte_gender_id has 1, 2, or 3. 1 = man, 2 = women 3 = undetermined and nd cte_from are age ranges.
So in the database: cte_gender_id is 1 and cte_from is 0
then anther row cte_gender_id is 1 and cte_from is 25
then another cte_gender_id is 1 and 35
and so on but with gender_id 2 and 3.
RegistrationController
$gender_ids = ['1', '2', '3'];
foreach ($gender_ids as $gender_id) {
$category = Categorie::where('cte_distance_id', $distance_id)
->where('cte_gender_id', $gender_id)
->where('cte_from',)
->first();
if (is_null($category)) {
return back()->with("errorMessage", "Category not found");
}
}
So I want if, for example, where gender_id is 1 and cte_from doesn't start with 0, it already doesn't go through.
You can use WHERE cte_from LIKE '0%' to test if a string starts with 0. In this query, % is used for a wildcard.
Or in Laravel query builder:
->where('cte_from', 'LIKE', '0%')
// Or if it doesn't start with a 0
->where('cte_from', 'NOT LIKE', '0%')

mysql join only returning the first row when it should be multiple

I am trying to retrieve information from two tables, user and meta. However, I am only getting the first row instead of all of them.
User table looks like this
ID | Display Name | Email
1 | Test | test#test.com
Meta table looks like this
meta_id | user_id | meta_key | meta_value
123 | 1 | address | 123 somewhere
123 | 1 | city | Metropolis
This is my query
$query = $this->db->from('users as u');
$query = $this->db->join('meta as m', 'u.ID = m.user_id');
$query = $this->db->where('ID', $data['ID']);
$query = $this->db->get();
return $query->row_array();
but I get everything for the user table, but only the first row of the meta table. Trying to get all the rows that match user_id = 1 in the meta table.
What am I missing in order for this to work?
Did you want to retrieve all result of the query or just the first row?
$query = $this->db->from('users as u');
$query = $this->db->join('meta as m', 'u.ID = m.user_id');
$query = $this->db->where('ID', $data['ID']);
$query = $this->db->get();
Getting just one result use:
row_array() returns a single result row. If your query has more than one row, it returns only the first row. The result is returned as an array.
return $query->row_array();
Getting an array of results use:
result_array() method returns the query result in pure array
return $query->result_array();
Try this. Hope it may be helpful
$this->db->select('u.*, m.*');
$this->db->from('users as u');
$this->db->join('meta as m', 'u.ID = m.user_id');
$this->db->where('u.ID', $data['ID']);
$query = $this->db->get();
return $query->row_array();
$this->db->reset_query();
$this->db->select("*");
$this->db->from('user');
$this->db->join('meta', 'user.id = meta.id ' );
$this->db->where('user.id="'. $data['ID'].'"'); // where conditions
$query = $this->db->get();
return $query->result();

CodeIgniter Active Record - Group OR statements

This is my problem: MySQL "Or" Condition
The solution is to group the OR statements, but i'm using CodeIgniters Active Record. Is there a way to group OR statements using Active Record? Or do I have to write the query myself?
I'm using $this->db->where() with $this->db->or_where()
It writes the query like this:
WHERE title = 'foobar' AND category = 2 OR category = 3
but what I need is:
WHERE title = 'foobar' AND (category = 2 OR category = 3)
I can't do this:
$this->db->where("title = 'foobar' AND (category = 2 OR category = 3)");
because i'm adding ORs using a foreach loop
You can do it manually as stated here:
Custom string: You can write your own clauses manually:
$where = "name='Joe' AND status='boss' OR status='active'";
$this->db->where($where);
As for your question:
$this->db->where("category = 1 AND (category = 2 OR category = 3)");
In 3.0-dev:
$this->db->select()
->group_start()
->or_like([ 'category' => 2, 'category' => 3 ])
->group_end()
->where([ 'category' => 1 ]);
update
See the answers on this question if you're using CI 2.2. Choose an answer other than the accepted.
Or simply try this:
$categories = array(2, 3);
array_walk($categories, function(&$cat) { $cat = 'category = ' . $cat; });
$catstring = implode(" OR ", $categories);
$where = "category = 1 AND ($catstring)";
// => category = 1 AND (category = 2 OR category = 3)
$this->db->where($where);
as OP mentioned you are generating OR using foreach (array)
you can simply use
$cat_array=array(2,3,4,5,6,7);
$this->db->select('col1, col2')->from('table')->where("col1",1)->where_in('col2', $cat_array);
will generate
SELECT `col1`, `col2` FROM (`table`) WHERE `col1` = 1 AND `col2` IN (2, 3, 4, 5, 6, 7)
you can't manipulate ground condition query using DB active record methods (where, or_where) , i would recommond to pass as sting in where() method
$this->db->where("category = 1 AND (category = 2 OR category = 3)");
In the Code Igniter Version 3.0-dev you can add groups in any query using group_start and group_end :
$this->db->select('col1, col2')
->where("category = 1")
->group_start()
->where("category = 2")
->or_where("category = 3")
->group_end();
Produces:
SELECT `col1`, `col2`
FROM `table_name`
WHERE category = 1 AND (category = 2 OR category = 3);

Retrieve data from table with foreign key

I was wondering how can I retrieve data from table3 with the use of 2 foreign keys. I will show you my tables first then try to explain what I am trying to do and how I am doing it.
Table1
ID Primary key
Table2
ID Foreign key
foodID Foreign Key
Table3
foodID Primary key
food
So I would first get the ID in the first table and compare it with the ID in the second table and get a foodID (note this relationship is a 1 to many, so I can have many foodIDs per ID). Then I want to output all foods by using the foodID. Heres an example of what I mean because I don't feel its too clear.
Say we have and ID = 1 and in this we have foodID = 1 and foodID = 2 and lastly foodID of 1 means food = pasta and foodID of 2 means food = mince meat. So in the end I would like to output both pasta and mince meat.
Heres the code I have so far, in the example above it will only output pasta and not mince meat:
public function getFood($id){
$data = $this->db->get_where('Table2', array('ID' => $id)); //Where $id is the ID in Table1
$Result = $data->result();
foreach($Result as $row){
$fID = $row->foodID;
}
$data = $this->db->get_where('Table3', array('foodID' => $fID));
return($data);
}
Heres my view where I output the food:
foreach($results as $row){
echo $row->food;
}
You just need to do a join:
public function getFood($id){
$this->db->select('*');
$this->db->from('Table3');
$this->db->join('Table2', 'Table2.ID = Table3.foodID');
$this->db->where('Table2.Id',$id);
$result = $this->db->get();
return $result;
}

Query issue in Codeigniter

I want to random show 6 news/reviews on my front page but it shows the same content 6 times random but I will not have duplication of content. Here is the SQL query:
SELECT
anmeldelser.billed_sti ,
anmeldelser.overskrift ,
anmeldelser.indhold ,
anmeldelser.id ,
anmeldelser.godkendt
FROM
anmeldelser
LIMIT 0,6
UNION ALL
SELECT
nyheder.id ,
nyheder.billed_sti ,
nyheder.overskrift ,
nyheder.indhold ,
nyheder.godkendt
FROM nyheder
ORDER BY rand() LIMIT 0,6
showing my example with active record for simplicity,
try randomizing your offset instead of the order, while still limiting to 6
// get the total number of rows
$total_rows = $this->db->count_all_results('my_table');
// offset random point within the total rows
$offset = rand( 0 , $total_rows - 6 );
$q = $this->db->offset( $offset )->limit( 6 )->get( 'my_table' );
print_r( $q->result_array() );
//initialize query builder
$sql1=$sql2=$this->db;
$sql1->select('anmeldelser.billed_sti ,anmeldelser.overskrift ,anmeldelser.indhold ,anmeldelser.id ,anmeldelser.godkendt');
$sql1->from('anmeldelser');
$sql1->order_by('rand()');
$sql1->limit(3);
//get only sql string
$query1=$sql1->get_compiled_select();
$sql2->select('nyheder.id ,nyheder.billed_sti ,nyheder.overskrift ,nyheder.indhold ,nyheder.godkendt');
$sql2->from('nyheder');
$sql2->order_by('rand()');
$sql2->limit(3);
$query2=$sql2->get_compiled_select();
//combine two query
$query = $this->mydb->query("($query1) UNION ($query2)");
$result = $query->result();
I am assuming that you need to join a Two table by this comment of yours.
You didn't mention your foreign key so I am assuming that also.
It is also not clear that the column name of your tables are same or not.
So, I am posting an join query for your table in which I assume your foreign key and column name, so please correct that before using it.
Here is your query to join your table:
$query = $this->db
->select('an.billed_sti,an.overskrift,an.indhold,an.id,an.godkendt, ny.id as ny_id,ny.billed_sti as ny_billed_sti, ny.overskrift as ny_overskrift, ny.indhold as ny_indhold , ny.godkendt as ny_godkendt ')
->from('anmeldelser as an')
->join('nyheder as ny', 'ny.id_fk = an.id', 'left outer') // I am assuming here that the [id_fk] field is the foreign key
->limit(0, 6)
->order_by('puttablename.tablecolumn', 'asc') // Your you table name and column name by which you want to order, you can use [asc/desc] as your need
->get();
And If you want to UNION here is the solution for it.

Categories