yii2 : add IFNULL exception to Command - mysql

i've create command and it works fine but when I add IFNull exception it add a comma and i searched a lot there is no answer my code :
public function actionTotal($id)
{
$query1 = new Query;
$query1 ->select(' sum(patient_services.price) price ,
sum( IFNULL(receipts.price,0)) receipts')
->from('patient_services')
->leftJoin('receipts', 'patient_services.patient_id = receipts.patient_id')
->where('patient_services.patient_id=:id', array(':id'=>$id));
$command1 = $query1->createCommand();
$price = $command1->queryAll();
echo Json::encode($price);
}
when i try it ... the select code have a comma and idon't know how to remove it
SELECT sum(patient_services.price) price, sum( IFNULL(receipts.price, `0))` AS `receipts` FROM `patient_services` LEFT JOIN `receipts` ON patient_services.patient_id = receipts.patient_id WHERE patient_services.patient_id=2

In you code
$query1 ->select('sum(patient_services.price) price
,sum( IFNULL(receipts.price,)) receipts')
^^ here is missing the value for ifnull
eg: ifnull(your_column, 0);
->from('patient_services')
->leftJoin('receipts', 'patient_services.patient_id = receipts.patient_id')
->where('patient_services.patient_id=:id', array(':id'=>$id));
then try
$query1 ->select(' sum(patient_services.price) price ,
sum( IFNULL(receipts.price,0)) receipts')
->from('patient_services')
->leftJoin('receipts', 'patient_services.patient_id = receipts.patient_id')
->where('patient_services.patient_id=:id', array(':id'=>$id));
looking at the strange result in your img
try using this this notation and (remove also the two space between query1 and ->
$query1->select(["sum(patient_services.price) AS price",
"sum( IFNULL(receipts.price,0)) AS receipts"] )
And eventually try to clear runtime directory ..and flush the db cache

Add 0 as a second parameter for IFNULL function, so that if the value is null it will print 0, here is the example.
$query1->select(['sum(patient_services.price) price,
sum( IFNULL(receipts.price,0)) receipts'])

Related

How to select multiple where conditions using codeigniter?

my table
This is my table i have to display the data using multiple where conditions. First i select using dms_expire_date,for this i got answer and i am using dms_doc_name in where conditions but i didn't got correct result.
I have tired so far.
]
See this picture if i use "or" in "where" i got testie not within this date.but if i use "and" in "where" i didn't got result for dms_expiry_date
See this picture
i don't know how to do this.please help to solve this problem.
SELECT * FROM `dms_document` WHERE dms_expire_date BETWEEN '2020-05-01' AND '2020-07-16' AND dms_doc_name = '' OR dms_category_id = '' OR dms_subcategory_id=''
I have tired in array also but i didn't result.
$this->db->select('*');
$this->db->join('dms_category as C', 'C.dms_category_id = D.dms_category_id', 'left outer');
$this->db->join('dms_sub_category as S', 'S.dms_subcategory_id = D.dms_subcategory_id', 'left outer');
$this->db->where('dms_expire_date >=', $newstart);
$this->db->where('dms_expire_date <=', $newend);
$this->db->where(array('dms_doc_name' =>$docname,'D.dms_category_id'=>$category,'D.dms_subcategory_id'=>$subcategory));
$data['documents']= $this->db->get('dms_document as D')->result_array();
try
SELECT *
FROM dms_document
WHERE dms_expire_date BETWEEN $newstart AND $newend
AND CASE WHEN $docname IS NULL THEN 1 = 1 ELSE dms_doc_name = $docname END
AND CASE WHEN $category IS NULL THEN 1 = 1 ELSE dms_category_id = $category END
AND CASE WHEN $subcategory IS NULL THEN 1 = 1 ELSE dms_subcategory_id = $subcategory END
--
edited. waiting for clearance.
if I get what you mean correctly, it is problem with understanding AND, OR, and the priority with brackets ()
--
if anyone want to use the fiddle, I have created the sample data for this issue
You can write OR using CodeIgniter's or_where() (v3 docs) or orWhere() (v4 docs).
//your initial query
$sql = "SELECT
*
FROM
`dms_document`
WHERE
dms_expire_date BETWEEN '2020-05-01' AND '2020-07-16'
AND dms_doc_name = ''
OR dms_category_id = ''
OR dms_subcategory_id=''";
//building the same query using CI
$this->db->select('*');
$this->db->from('dms_document');
$this->db->where('dms_expire_date >=', '2020-05-01');
$this->db->where('dms_expire_date <=', '2020-07-16');
$this->db->where('dms_doc_name', '');
$this->db->or_where('dms_category_id', '');
$this->db->or_where('dms_subcategory_id', '');
You can confirm the query this generates by running $this->db->_compile_select(); or $this->db->last_query(); (https://stackoverflow.com/a/6145021/1499877 for reference).
echo '<pre>';
var_dump($sql);
var_dump($this->db->_compile_select());
echo '</pre>';
die();

Codeigniter's Model with QueryBuilder JOIN query

Really new to working with CI4's Model and struggling to adapt my existing MySQL JOIN queries to work with the examples in its User Guide.
I have adapted part of my code like so:
public function brand_name($brand_name_slug)
{
return $this->asArray()
->where('availability', 'in stock')
->where('sku !=', '')
->where('brand_name_slug', $brand_name_slug)
->groupBy('gtin')
->orderBy('brand_name, subbrand_name, product, size, unit')
->findAll();
}
It works fine. I have looked at examples, and figured out I can add the code ->table('shop a') and it still works, but I also need to to add the following JOIN statement:
JOIN (SELECT gtin, MIN(sale_price) AS sale_price FROM shop GROUP BY gtin) AS b ON a.gtin = b.gtin AND a.sale_price = b.sale_price
As soon as I add ->join('shop b', 'a.gtin = b.gtin and a.sale_price = b.sale_price') I get a '404 - File Not Found' error.
When I look at all examples of CI4 joins and adapt my code to fit, my foreach($shop as $row) loop generates a 'Whoops...' error because they end with a getResult() or getResultArray - instead of findAll().
Which is the way forward, and do I need to change my foreach loop.
Full MySQL statement:
SELECT * FROM shop a JOIN (SELECT gtin, MIN(sale_price) AS sale_price FROM shop GROUP BY gtin) AS b ON a.gtin = b.gtin AND a.sale_price = b.sale_price WHERE availability = 'in stock' AND sku != '' AND brand_name_slug = $brand_name_slug GROUP BY gtin ORDER BY brand_name, subbrand_name, product, size
Query builders have their limits. That's why the query method exists. If you have a complex query I'd advise you to just use $this->query();.
It will make you lose less time and effort converting something you know already works. And in the top of that, while converting complex queries you usually end up using the query builder but with big part of your SQL in it.
In your model extending CodeIgniter\Model :
$query = $this->db->query("SELECT * FROM shop a JOIN (SELECT gtin, MIN(sale_price) AS sale_price FROM shop GROUP BY gtin) AS b ON a.gtin = b.gtin AND a.sale_price = b.sale_price WHERE availability = 'in stock' AND sku != '' AND brand_name_slug = \$brand_name_slug GROUP BY gtin ORDER BY brand_name, subbrand_name, product, size");
// your array result
$result_array = $query->getResultArray();
// your object result
$result_object = $query->getResult();
BaseBuilder Class in Codeigniter expects the first join parameter to be the table name. So try passing the table name and join it on the table name itself. I haven't personally used the table aliases so I might also be wrong.
Following are the parameter that the JOIN query expects :
public function join(string $table, string $cond, string $type = '', bool $escape = null)
Here, it expects the first name be a table, so try out by switching aliases for the table's name directly.
For your second part of query, It would be better if you could show the whole error rather than just posting the first of the error.
Managed to figure it out in the end:
public function brand_name($brand_name_slug)
{
return $this
->db
->table('shop a')
->select()
->join('(SELECT sku, MIN(sale_price) AS sale_price FROM shop GROUP BY sku) AS b', 'a.sku = b.sku AND a.sale_price = b.sale_price')
->where('availability', 'in stock')
->where('a.sku !=', '')
->where('brand_name_slug', $brand_name_slug)
->groupBy('a.sku')
->orderBy('brand_name, subbrand_name, product, size, unit')
->get()
->getResult();
}
Thanks for all your pointers!

yii2 : remove comma from createCommand

i've create a Command in my controller like this :
public function actionTotal($id)
{
$query1 = new Query;
$query1 ->select('sum(patient_services.price) price, sum(receipts.price) receipts ,')
->from('patient_services ')
->leftJoin(' receipts ON patient_services.patient_id=receipts.patient_id')
->where('patient_services.patient_id=:id', array(':id'=>$id));
$command1 = $query1->createCommand();
$price = $command1->queryAll();
echo Json::encode($price);
}
when i try it ... the select code have a comma and idon't know how to remove it
SELECT sum(patient_services.price) price, sum(receipts.price) receipts FROM `patient_services` LEFT JOIN ` receipts ON` `patient_services`.`patient_id=receipts`.`patient_id` WHERE patient_services.patient_id=1
when i remove all commas from the sql code and try it in phpmyadmin .. it works fine :(
You have an invalid leftJoin replace it with this:
->leftJoin('receipts', 'patient_services.patient_id = receipts.patient_id')
also it seems you have an extra comma at the end of your select query remove that last comma the select query would look like this:
$query1 ->select('sum(patient_services.price) price, sum(receipts.price) receipts')
Hope this works.

Perform arithmetic within MySQL UPDATE query formed using CodeIgniter's Active Record class

I'm using $this->db->update(); to create an update query that adds the value stored in a variable, $amount, to the value in a column, count. My function call currently looks like this:
$data = array('count' => 'count + '.$amount);
$this->db->where('id', $item_id);
$this->db->update('items', $data);
However, this generates the following broken SQL:
UPDATE `items` SET `count` = 'count + 2' WHERE `id` = '2'
Is there a way to generate the SET clause without the quotes around count + 2?
Thanks, Maxime Morin, for putting me on the right track. According to the CodeIgniter Documentation, you can create a "set" clause without quotes by setting the optional $escape parameter to FALSE. Thus, the solution to my problem was:
$this->db->set("count", "count + $amount", FALSE);
$this->db->where("id", $item_id);
$this->db->update("items", $data);
Here's the work-around I used until I found my accepted solution
$query = $this->db->query("UPDATE `items` SET `count` = `count` + $amount WHERE `id` = $item_id");

SQL: How to use SELECT results as function input parameters

Here is my query:
SELECT
CASE
WHEN hbn.users.showDistance = 'T'
THEN hbn.distance(u2.lat, u2.lon, hbn.users.lat, hbn,users,lon)
ELSE 0
END as distance,
hbn.users.id,
hbn.users.username,
From hbn.users,
(select hbn.users.lat, hbn.users.lon from hbn.users where hbn.users.id = '1') AS u2
where hbn.users.Id = '8';
This does not work!
I need to use output of the second select statement as input for distance() function.
It looks like you have commas instead of full-stops in the last parameter to hbn.distance?