I'm working with CodeIgniter and Active Record (mysql database), to write a special query. Here is the working query :
$this->db->select('moo_aauth_users.*', false);
$this->db->select('moo_tasks.id AS task_id, moo_tasks.user_id, moo_tasks.task_status, moo_tasks.task_type, moo_tasks.skill_category, moo_tasks.tasker_hired, moo_tasks.task_city_id, moo_tasks.completed, moo_tasks.hours_spend, moo_tasks.additional_fees, moo_tasks.total_price, moo_tasks.paid, moo_tasks.tasker_asked_id, moo_tasks.tasker_asked_response, moo_tasks.tasker_asked_rate, moo_tasks.title, moo_tasks.description, moo_tasks.expiration_date, moo_tasks.telephone, moo_tasks.zipcode, moo_tasks.address, moo_tasks.created_stamp, moo_tasks.updated_stamp, moo_tasks.assigned_stamp, moo_tasks.completed_stamp, moo_tasks.provider, moo_tasks.country, moo_tasks.task_zone', false);
$this->db->from('moo_tasks');
$this->db->join('moo_aauth_users', 'moo_aauth_users.id = moo_tasks.user_id');
$this->db->where('moo_tasks.task_status', TASK_STATUS_PENDING);
But now, I would like to add a special where clause based on another table.
I have a table moo_offers containing different offers corresponding to a task. In my query, I want to check if the task I'm retrieving DOES NOT contains a corresponding offer in the moo_offers table.
Example :
moo_tasks: id 1 / ...
moo_tasks: id 2 / ...
moo_offers: task_id 1 / ..
With the query, only moo_tasks.id = 2 will be retrieved, not the id 1 because it has an offer in the second table.
I tried multiple thinks in my query, but did'nt works :
$this->db->join('moo_offers', 'moo_offers.id_task = moo_tasks.id');
$this->db->where('moo_offers.id_tasker NOT IN (SELECT `id_tasker` FROM `moo_offers` WHERE id_task = moo_offers.id_task && id_tasker = '.$filter['tasker_id'].')', NULL, FALSE);
Have you and idea please? Thanks!
$this->db->select('*');
$this->db->from('tbl_user');
$this->db->join('tbl_userinfo', 'tbl_user.user_id = tbl_userinfo.user_id');
$this->db->where('tbl_user.user_id', $data);
$query = $this->db->get();
$result = $query->result();
return $result;
this is what i did and it worked.
Related
"Table1":
id
name
1
Ulrich
2
Stern
"Table2":
id
school
tid
1
A
1
2
B
1
I want to join 2 table to get all information. With SQL query like this:
SELECT Table1.id,
name,
school
FROM `Table1`
INNER JOIN `Table2`
ON Table1.id = Table2.tid
It gives me all information as I expect (I mean 2 rows with name 'Ulrich').
But when I do with Yii2 query:
$query = self::find();
$query -> alias('t1')
-> innerJoin(['t2'=>'Table2'], 't1.id=t2.tid')
$result = NULL;
if($total = $query->count()) {
$result = $query
-> select([t1.*, t2.school])
->asArray()
->all()
;
$result[0]['count'] = $total;
}
it only gives me 1 row with name 'Ulirch'.
Can anyone help me with this problem. Thank you very much.
If you use ActiveRecord::find() method to create query you will get instance of yii\db\ActiveQuery. This is query designed to load ActiveRecord models. Because of that if you do any type of join and your result set contains primary key of your main model (The model which find() method was called to create query) the ActiveQuery will remove any rows it considers duplicate.
The duplicates are recognised based on main model primary key so the rows in resultset will be considered duplicate even if the data from joined table are different. That's exactly what happened in your case.
To avoid that you have to use query builder instead of ActiveQuery.
Your query can look for example like this:
$query = (new \yii\db\Query())
->from(['t1' => self::tableName()])
->innerJoin(['t2'=>'Table2'], 't1.id=t2.tid');
I got two table which I would like to query from, which the users table and the user_job table
users table structure
user_job table
What I want to achieve is to write a MySQL query in CodeIgniter to display user information from users table if user_status in users table is "Active" And if there is no row in user_job table where user_job_status is equal to "On Probation" or user_job_status is equal to "Active"
In simple English, I want to display a user information if a user not currently on a job.
My current Codeigniter Model code is:
//get all user that are not currently assigned to a position
function get_idle_user(){
$this->db->select('*');
$this->db->from('users');
$this->db->join('user_job', 'user_job.user_id_fk = users.user_id', 'INNER');
$this->db->where('users.user_status','Active');
$this->db->where("(user_job.user_job_status != 'Active' OR user_job.user_job_status != 'On Probation')", NULL, FALSE);
$this->db->group_by('users.user_id');
if($query = $this->db->get()){
return $query;
}else{
return false;
}
}
The problem with this code that it will still display user information if there is a row related to a user and user_job_status does not satisfy the where condition above.
Please Help.
I believe this is what you are after ...
$db->select('user_id_fk,COUNT(*) as `Tally`');
$db->where('user_job_status','On Probabtion');
$db->or_where('user_job_status','Active');
$db->group_by('user_id_fk');
$sub = $db->get_compiled_select('user_job_table');
$db->join("($sub) ujt",'ujt.user_id_fk = users.user_id AND Tally = 0','left');
$db->where('user_status','Active');
// View this query in full
//echo $db->get_compiled_select('users_table');
// Get the data
$data = $db->get('users_table')->result_array();
Note:
You don't need select('*') - it isn't needed
You don't need ->from() - it can be used in the get() element
I have left in the get_compiled_select which will allow you to see the full query and get an idea what its doing. You should comment out the $data line if you uncomment the echo line.
What this query is doing is saying get all users from the job_table which don't have the status Active or On Probation and a list of User ID's. That way you can then get Active users from the users_table and users with a tally of 0.
is it possible to pass the variable value in mysql query in codeigniter ?
I want to select records from database that have id same as my session id.
my code is :
$this->db->select('*'); // <-- There is never any reason to write this line!
$this->db->from('products');
$this->db->where('id_admin = (SELECT id_admin FROM users WHERE id='.$this->session->userdata('user_id').')', NULL, TRUE);
can we concatenate variable values in database queries?
This code not given any error, but not give any result also.
Use join in active records
$this->db->select('p.*');
$this->db->from('products as p');
$this->db->join('users','p.id_admin=users.id');
$this->db->where('users.id',$this->session->userdata('user_id'),false);
$query = $this->db->get();
An Example Reference of how to write the JOIN Query in CI as per the Documentation of the Active Records.
$article_id = $this->input->post('article_id');
$this->db->select('*');
$this->db->from('articles');
$this->db->join('news', 'news.id = articles.id');
$this->db->where('articles.id',$article_id);
$query = $this->db->get();
The above code will produce the query as follows for execution.
SELECT * FROM articles JOIN news ON news.id = articles.id WHERE articles.id='10'
Provided the passed id is 10
In order to view the Result of the executed query you must perform the below code.
print_r($query->result());
Try like this..use joining of two tables.
<?php
$this->db->select('products.*');
$this->db->from('products');
$this->db->join('users','products.id_admin=users.id_admin');
$this->db->where('users.id',$this->session->userdata('user_id'));
$query = $this->db->get();
print_r($query->result_array());//your array of records
I want to delete from ‘table1’ those rows where (user_id = 5) but I should check if those posts’ (title = title1 in table2). I use Codeigniter and I get this error while trying to delete: ‘Deletes are not allowed unless they contain a "where" or "like" clause.’ Could you please help me to check what is wrong with my code below.
table1:
table2:
public function delete($title, $user_id){
$this->db->select('table1.*');
$this->db->from('table1','table2');
$this->db->where('table1.user_id', $user_id);
$this->db->where('table2.title', $title);
$this->db->join('table2','table1.post_id=table2.post_id');
$query = $this->db->get();
if ($query && $query->num_rows() > 0) {
$this->db->delete('table1.*');
$this->db->from('table1','table2');
$this->db->where('table1.user_id', $user_id);
$this->db->where('table2.title', $title);
$this->db->join('table2','table1.post_id=table2.post_id');
return true;
}
else {
return false;
}
}
Make use of subqueries.
example
#Create where clause
$this->db->select('id');
$this->db->from('table2');
$this->db->where('table2.title', $title);
$where_clause = $this->db->get_compiled_select();
#Create main query
$this->db->where('table1.user_id', $user_id);
$this->db->where("`id` NOT IN ($where_clause)", NULL, FALSE);
$this->db->delete('table1');
References
stolen from here: https://stackoverflow.com/a/16303021/1275832
about subqueries: http://www.mysqltutorial.org/mysql-subquery/
compiled select: https://github.com/NTICompass/CodeIgniter-Subqueries
After running first query you will get the set of user that you have to delete.
Run this set throw foreach loop for getting id of user and posts that you have to delete to an array.
$user_array = array();
$post_array = array();
foreach($query->result() as $query)
{
$user_array[$query->user_id] = $query->user_id;
$post_user[$query->post_id] = $query->post_id;
}
And then
this->db->where_in('user_id', $user_array)->delete('table1');
this->db->where_in('post_id', $post_array)->delete('table2');
I know that this is not the best decision. But i think that this is the most understandable.
You may use the following code to delete data from tables becasue codeigniter ignore join when you delete multiple data from multiple tables.
$sql = "DELETE t1 FROM table1 t1
JOIN table2 t2 ON t1.thing_id = t2.id
WHERE t2.otherthing_id = ?";
$this->db->query($sql, array($id));
JOINS are used to fetch data from database not used to delete data if you want to delete data from multiple table using single query then you need to use cascading in MySQl using that you can delete data also from other tables that are related to current table.
I need to select category ids from my sql database.
I have a variable $product_id and for each product id there are three rows in a table that i need to select using PHP.
If I do "SELECT * FROM table_name WHERE product_id='$prodid'"; I only get the one on the top.
How can I select all three category_ids which contain the same product_id?
I suppose you are using PHP's mysql functions, is this correct? I am figuring that your query is actually returning all three rows but you aren't fetching all of them.
$sql = "SELECT * FROM table_name WHERE product_id='$prodid'";
$r = mysql_query($sql, $conn); //where $conn is your connection
$x = mysql_fetch_SOMETHING($r); //where something is array, assoc, object, etc.
The fetch function gives only one row at a time. You say you need three so it needs to be executed three times.
$x[0] = mysql_fetch_assoc($r);
$x[1] = mysql_fetch_assoc($r);
$x[2] = mysql_fetch_assoc($r);
OR this would be better
while($curRow = mysql_fetch_assoc($r)) //this returns false when its out of rows, returns false
{
$categoryIds[] = $curRow['category_id'];
}
If this doesn't do it then your query is actually returning only one row and we need to see your tables/fields and maybe sample data.
SQL seems to be correct, but Why do you store product_id in categories table? if it's one-to-many relation it would be better to store only category_id in products table.
The SQL query is correct for what you want to do. It will select all the records in table_name with the field product_id = $prodid (not only 1 or 3 but any that matches the variable)
To select a few records you should use the LIMIT keyword
You should look inside your table structure and the variable $prodid to find problems.