How can I pass an array variable in where clause with codeigniter?
For example with a SQL query like:
Select(" item,price Where(userid=123 and proid=3 or userid=124 and proid=3... [upto n user id]userid=nth_id and proid=3");
If userid is stored in an array variable then how can I create such a condition in codeigniter?
I you are looking for this, it should look for a userid that is in the array and also has a proid of 3. I have not tested it but let us know how you get on.
$array = array( '123', '124' );
$this->db
->select( 'item, price' )
->from( 'table')
->where( 'proid', '3' )
->where_in( 'userid', $array )
->get();
$result = $query->result();
Related
I am having trouble with my query since I really don't know what to write. I want to get value from the database from my data which is inside an array separated by comma.
Let's say I have this method on my controller
query_array = array(
'tags' => explode("%2C", $this->input->get('tags'))
);
Then currently I have this query on my model.
if(strlen($query_array['title'])) {
$this->db->select("
si.song_info_file_name AS filename,
si.song_info_revised_file_name AS revised_filename,
si.song_info_original_title AS title,
a.artist_name AS artist,
si.song_info_id AS songinfoid,
array_to_string(array_agg(c.composer_name),'/') AS composer,
array_to_string(array_agg(p.publisher_name),'/') AS publisher,
array_to_string(array_agg(st.tag_name),',') AS tags"
);
$this->db->from('song_info si');
$this->db->join('original_artist a', 'si.artist_id = a.artist_id', 'left');
$this->db->join('composer c', 'si.composer_id = c.composer_id', 'left');
$this->db->join('publisher p', 'si.publisher_id = p.publisher_id', 'left');
$this->db->join('song_info_tags sit', 'si.song_info_id = sit.song_info_id', 'left');
$this->db->join('song_tags st', 'st.tag_id = sit.tag_id', 'left');
$this->db->like('LOWER(a.artist_name)', strtolower($query_array['title']));
$this->db->group_by(array("si.song_info_id", "a.artist_name", "c.composer_name" , "p.publisher_name" ));
$query = $this->db->get();
return $query->result_array();
}
The value of 'tags' => explode("%2C", $this->input->get('tags')) is Array ( [0] => 4,10,11,14 ) if I already explode it. my question now is that how would I be able to add this to my select LIKE criteria? for example LIKE tag_id = from the result of the array. I really need some help since I'm stuck with this one for kinda while now.
I have to execute this query
select count(id) as numberofcompanies, sum(offered_value) as total_offered_value from campaign_comapany
where ( campaign_id in (select id from campaing where user_id = current_user ) or campaing_company.sp_user_id = current_user)
and campaign_company.status = '3'
And I wrote the query like this in yii2-
$query->select(['count(id) as numberofcompanies','sum(offered_value) as total_offered_value'])
->from('campaign_company')
->andFilterWhere(['or',['in','campaign_id',(new yii\db\Query())->select(['id'])->from('campaign')->where(['=','user_id',Yii::$app->user->id])],['=','campaign_company.sp_user_id',Yii::$app->user->id]])
->andWhere(['=','status','3'])
->one();
But it gives me error with unknow column campaign_company.user_id
but working if I just use where like following-
$query->select(['count(id) as numberofcompanies','sum(offered_value) as total_offered_value'])
->from('campaign_company')
->where(['in','campaign_id',(new yii\db\Query())->select(['id'])->from('campaign')->where(['=','user_id',Yii::$app->user->id])])
->andWhere(['=','status','3'])
->one();
What should I do to get the result mentioned sql query, I don't want to hit database server two time, thanks in advance
Use join:
$query->select(['count(id) as numberofcompanies','sum(offered_value) as total_offered_value'])
->from('campaign_company')
->innerJoin('campaign','`campaign`.`id` = `campaign_company`.`campaign_id`')
->where([
['=','campaign.user_id',Yii::$app->user->id])],
['=','campaign.campaign_company.sp_user_id',Yii::$app->user->id],
['=','campaign_company.status','3']
]
->one();
As is it is difficult to follow your logic. To simplify your code and your query, add the first condition as plain sql. Also since the second condition is required, you can swap the positions as follows:
$query
->select(['count(id) as numberofcompanies','sum(offered_value) as total_offered_value'])
->from('campaign_company')
->where(['status' => '3'])
->andWhere(['
campaign_id in (select id from campaign where user_id = :current_user )
or campaign_company.sp_user_id = :current_user1',
[':current_user' => Yii::$app->user->id, ':current_user1' => Yii::$app->user->id]])
->one();
I will try below query, but not sure is prevent sql injection?
$status = [1, 2, 3];
$param = implode(', ', $status);
$rows = (new \yii\db\Query())
->select('*')
->from('user')
->leftJoin('post', "post.user_id = user.id AND post.some_column = $value AND post.status IN ($param)");
->all();
return expected results but may be occur sql injection. My IN condition look like is IN (1, 2, 3)
$rows = (new \yii\db\Query())
->select('*')
->from('user')
->leftJoin('post', "post.user_id = user.id AND post.some_column = :sid AND post.status IN (:param)", [':param' => $param, ':sid' => $value]);
->all();
only compare first element in array because is look like this IN ('1, 2, 3') its consist single string not check second element in array only work on first element.
I refer below link but no idea for how to implement this condition.
Can I bind an array to an IN() condition?
Please give the solution for how to use IN() Condition in On part of join(PDO/Yii2/mysql).
Based on this issue:
$rows = (new \yii\db\Query())
->select('*')
->from('user')
->leftJoin('post', ['post.user_id' => new \yii\db\Expression('user.id'), 'post.some_column' => $sid, 'post.status' => $statuesArray]);
->all();
Yii2 can create a parametrized IN condition by passing the condition as an array i.e:
['post.status' => $status]
However, converting your join condition to the array format will not work as explained in the Yii guide:
Note that the array format of where() is designed to match columns to values instead of columns to columns, so the following would not work as expected: ['post.author_id' => 'user.id'], it would match the post.author_id column value against the string 'user.id'. It is recommended to use the string syntax here which is more suited for a join:
'post.author_id = user.id'
Since you are using an INNER JOIN the result of putting the join condition in WHERE instead of in ON will be syntactically equal as explained in INNER JOIN condition in WHERE clause or ON clause?. For readability and ease of maintenance, you can leave the comparison for the tables columns in the join condition:
$rows = (new \yii\db\Query())
->select('*')
->from('user')
->innerJoin('post', 'post.user_id = user.id')
->where(['post.some_column' => $value, 'post.status' => $status])
->all();
I am trying to run a query. I have two many to many entities.
My query for these both entities below
$query = $user->createQueryBuilder('u')
->join('u.products', ua')
->Where('ua.id In (:uproducts)')
->setParameters(array(
'uproducts' => $userproducts ))
->getQuery();
$query = $user->createQueryBuilder('u')
->join('u.price,'up')
->Where('up.id In (:uprice)')
->setParameters(array(
'uprice'=>$userprice))
->getQuery();
If i do that in two queries like that it works. But I want that in 1 select query. Is there any idea how I could do that?
Thanks in advance.
Try this :
$query = $user->createQueryBuilder('u')
->join('u.products', 'ua')
->join('u.price,'up')
->Where('ua.id In :uproducts')
->andWhere('up.id In :uprice')
->setParameters(
array (
'uproducts' => $userproducts,
'uprice'=>$userprice
)
)
->getQuery();
I simply want to return all rows from a users table but selected fields, and possible concat 2 fields.
normal sql could have just been:
SELECT id, CONCAT(`first_name`,`last_name`) AS `fullname` FROM `users`
But trying to achieve this in cake is a nightmare:
$users = $this->User->find("all") = returns everything
$users = $this->User->find("list",array("fields" => " ...) does not work either.
Can anyone please help me on how to use the cake model to achieve the simple query and return results
You are close:
$this->User->find('all', array('fields' => array('CONCAT(first_name,last_name) AS fullname', 'otherfield'), 'contain' => array());