Laravel MySQL with where conditions avoid columns - php

I want to perform following search query, when user sends values I want to get matching results
If any results contain "none" i want to remove it from where condition and check only matching values for others
Example 1
$fructose = high
$lactose = mid
$polyols = none
$fructan = none
if so i want to check only matching results for $fructose=high and $lactose=mid
Example 2
$fructose = high
$lactose = mid
$polyols = mid
$fructan = mid
If so I want to check all matching results
Please advise, below is my current query
$fod = FodMap::select('*')
->where('fructose_level', '>=', $fructose)
->where('lactose_level','>=', $lactose)
->where('polyols_level', '>=', $polyols)
->where('fructan_level', '>=', $fructan)
->get();

Here I tried to solve your problem by writing query using eloquent structure. You should manage value and operator in where condition as per your need.
You can write your query with if condition like this:
$query = FodMap::select('*');
if($fructose != none){
$query = $query->where('fructose_level',$fructose);
}
if($lactose != none){
$query = $query->where('lactose_level',$fructose);
}
if($polyols != none){
$query = $query->where('polyols_level',$fructose);
}
if($fructan != none){
$query = $query->where('fructan_level',$fructose);
}
$fod = $query->get();

Related

IN clause is not working properly in MYSQL php

I have a sql query like this
$statusData = $DB->get_records_sql("SELECT id, element, value FROM {scorm_scoes_track} WHERE scormid = ? AND userid = ? AND element =$DB->get_in_or_equal('cmi.core.lesson_status','cmi.core.total_time')", array($scorm_id, $userid) );
So i am trying to fetch the values from query
<?php
$statusData = reset($statusData);
if($statusData->element == 'cmi.core.lesson_status')
$status = $statusData->value ;
elseif($statusData->element == 'cmi.core.total_time')
$totaltimes = $statusData->value ;
but its just showing only status value..it's not showing total time value..Can any one help me
Thanks in advance..
You do not have any in operator in your code, so there is nothing that could work at all as an in!
Replace the = with in and remove the moodle call as well as shown below:
...AND element IN ('cmi.core.lesson_status','cmi.core.total_time')

Mysql query for Comma separated values in columns and aslo in search keywords

I have one condition in query where I want to search results.
In database there is region column in which region is saved as comma separated.
And user select multiple regions which I get in comma separated format.
How can I compare column value and search values.
I want query in codeigniter.
$search_id2 = "01,02,03";
$this->db->select('posting_id,short_desc, doc_last, country');
$this->db->from('abc');
$this->db->like('region', $search_id2);
$query = $this->db->get();
I just try to answer your problem.
You can use explode()
$search_id2 = "01,02,03";
$search_id2 = explode(",",$search_id2)
$this->db->select('posting_id,short_desc, doc_last, country');
$this->db->from('abc');
foreach ($search_id2 as $key) {
$this->db->or_like('region', $key);
}
$query = $this->db->get();
as neodan suggested in the comments you can use find in set
something like that should do the job
$search_id2 = "01,02,03";
$arrSearchIds = explode(",",$search_id2);
$this->db
->select('posting_id,short_desc, doc_last, country')
->from('abc')
->group_start();
if (count($arrSearchIds) > 0)
{
foreach($arrSearchIds AS $id)
{
$this->db->or_where("find_in_set(".$id.", region)", NULL, false);
}
}
$this->db->group_end();
$query = $this->db->get();

WHERE_IN returns only first match in codeigniter

I am trying to get a list of coupons through ajax when the checkboxes are selected. So everything else is working fine but the query is returning only the first match.
So my query is:
$this->db->from('tbl_coupons');
if($storeids !=''){
$ids = array($storeids);
$this->db->where_in('coupon_store', $ids );
}
$this->db->where('coupon_cat', $catid);
$this->db->where('coupon_status', 'active');
$query = $this->db->get();
if ($query->num_rows() > 0) {
$ds = $query->result_array();}
According to this my SQLquery becomes
SELECT * FROM `tbl_coupons`
WHERE `coupon_store` IN('1,97')
AND `coupon_cat` = '16'
AND `coupon_status` = 'active'
But this query is returning values with coupon_store=1 and no results are coming for coupon_store=97
I checked values for coupon store 97 which exists in that category.
use below way if data exist it will be part of query.
storeids = explode(',',storeids);
$ids = array();
foreach($storeids as $val){
$ids[] = $val;
}
if(!empty($ids)){
$this->db->where_in('coupon_store', $ids );
}
hope it will create proper sql query
The query is mostly correct, except at line 2, where you need to make the change as:
WHERE coupon_store IN('1','97')
everything else remains the same.

count and check json query result

I am handling three scenarios :
1) If query returns no result
2) if query returns one result
3) if query returns two or more result
This is my query :
$events = DB::table('bookings')
->join('events','bookings.event_id','=','events.id')
->join('spots','bookings.spot_id','=','spots.id')
->join(DB::raw('(select S.event_id,sum(S.spaces) as sum_spaces from spots S group by S.event_id) d'), function($join)
{
$join->on('bookings.event_id', '=', 'd.event_id');
})
->select('bookings.event_id','events.name', 'spots.event_date','d.sum_spaces',
DB::raw('COUNT(bookings.event_id) as tb'))
->groupBy('bookings.event_id')
->get();
I get $events in json format like this :
[] = 0
[{"event_id":1,"name":"Yoga","event_date":"2016-05-02","sum_spaces":"450","tb":6}] = 1
[{"event_id":1,"name":"Yoga","event_date":"2016-05-02","sum_spaces":"100","tb":16},{"event_id":2,"name":"Yoga","event_date":"2016-05-02","sum_spaces":"450","tb":6},{"event_id":3,"name":"blah","event_date":"2016-05-02","sum_spaces":"250","tb":6}] = 3
If you see that 0,1 and 3. thats what I want to know for a given resultant query.
I need to check if the above result has how many results. How can I find this
Because this is how I am handling the scenarios :
if(empty($events))
{
//sets default value
}
else if(check if $results have one and only one result)
{
//Do something
}
else
{
//here I can handle if $events query have more than one result.
}
If I understood you correctly, you need to count() them:
$numberOfResults = count($events);

Yii createCommand not not returning correct results

I am trying to get a random ID from a table with a specific visiblity=2 clause but I am having issues getting it to return the ID, it says Undefined index: id.
$space = Yii::app()->db->createCommand()
->select('id')
->from('space')
->where('id=rand() AND visibility=2')
->limit(1)
->queryAll();
//->queryRow();
echo $space['id'];
Is his not the correct way?
I figured out another solution using the already loaded info from my original version without guest check.
$max = Space::model()->count();
$randId = rand(0,$max);
$space = Space::model()->find(array('offset'=>$randId));
if ($space->attributes['visibility'] == 2) {
You can use ORDER BY RAND() instead of id = rand(). Also you can use ->queryScalar() to get only ID directly.
$space = Yii::app()->db->createCommand()
->select('id')
->from('space')
->where('visibility = 2')
->order('RAND()')
->limit(1)
->queryScalar();
echo $space;
Keep in mind that RAND() is slow solution. Check alternatives.
Also, if you get no entries from database, you have to check that case:
if (!empty($space)) { // id will never be 0
// Do something with $space
} else {
throw new CHttpException(404, 'No data found');
}
You are using the random id in where clause, therefore $space maybe an empty array based on condition. For example if you don't have a record with id == 3 and random generated id is 3, then $space is an empty value. So $space['id'] cause Undefined index error. You need to make sure the array is not empty and then echo id of array:
if($space != null)
echo $space['id'];
queryAll method gives you an array with database objects.
For your purpose you can use simpler and more understandable code:
$spaceId = Yii::app()->db->createCommand()
->select('id')
->from('space')
->where('visibility=2')
->orderBy(RAND())
->limit(1)
->queryScalar();
echo $spaceId;

Categories