SQL Server query on php - php

I'm begginner in this field so I need help.
I want to get integer value from this select. When I run this query in sql server - it returns correct value (so that part is okay)
My idea is to get integer value of $select -> put it in $value variable and use it after that.
Here is working sql expression:
$select = "SELECT COUNT (*) broj (SELECT a.CaseNo as CaseNo,
b.Naruc as Naruc,
b.Opis as Opis,
b.Vrijednost as cijena,
CONVERT(VARCHAR(50),b.Datumpn, 127) as datum_predaje,
(case when b.Kn IS NULL then 0 when b.Kn IS not null then b.Kn end) as kat1,
(case when b.Kn2 IS NULL then 0 when b.Kn2 IS not null then b.Kn2 end) as kat2,
(case when b.Kn3 IS NULL then 0 when b.Kn3 IS not null then b.Kn3 end) as kat3,
a.DateInserted as datum_unosa
FROM [Therefore].[dbo].[za_slanje_maila] a, [Therefore].[dbo].[TheCase1] b
WHERE CONVERT(date,a.DateInserted) = '".$today."'
AND a.DateInserted < '".$today3."'
AND a.CaseNo = b.CaseNo
AND b.Naruc is not null
AND b.Opis is not null
AND b.Vrijednost is not null
AND b.Datum_predaje is not null) broj";
After that, I tryed this
$data_api = sqlsrv_query($conn, $select, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
And then I try to call
$value = $data_api['broj']
- but that is empty.
How can I assign that value to the variable $value?
Thanks.

sqlsrv_query() doesn't return an array yet, but statement resource (or false on error). You can then use this resource to get the data array with sqlsrv_fetch_array() function.

Related

Returning Data From from a Sub-query With fetchcolumn()

I am trying to simply my code. I know this works and will return a value for $waiver_cash:
$waiver_query = $pdo->prepare("SELECT cap_number + waiver_number - :salary -
(SELECT sum(current_salary)
FROM salaries
WHERE gm = :gm AND franchise IS NULL AND waiver_bid IS NULL) -
(SELECT COALESCE(sum(waiver_bid), 0) FROM salaries
WHERE gm = :gm) AS waiver_cash
FROM base_numbers;");
$waiver_query->execute(['salary' => $salary, 'gm' => $gm]);
foreach ($waiver_query as $row) {
$waiver_cash = $row['waiver_cash'];
}
However, what I want to do, is this:
$waiver_query = $pdo->prepare("SELECT cap_number + waiver_number - :salary_retained -
(SELECT sum(current_salary)
FROM salaries
WHERE gm = :gm AND franchise IS NULL AND waiver_bid IS NULL) -
(SELECT COALESCE(sum(waiver_bid), 0)
FROM salaries
WHERE gm = :gm) AS waiver_cash
FROM base_numbers;");
$waiver_query->execute(['salary_retained' => $salary_retained, 'gm' => $gm]);
$waiver_cash = $waiver_query->fetchColumn();
When I do it with "fetchColumn()" nothing gets returned. Other than changing the $pdo->prepare to $pdo->query and putting the variables in the SELECT statements, is what I want to do, possible?
I found the issue. I have another query which fetches the data for $salary_retained.
$salary_retained_query = $pdo->prepare("SELECT COALESCE(sum(current_salary), 0) FROM salaries WHERE salary_retained= :gm;");
$salary_retained_query->execute(['gm' => $gm]);
$salary_retained = $salary_retained_query->fetchColumn();
Some of the GMs didn't have any criteria which matched and so the value returned was "null". Then in the query which I was having issues, the sum was returning a null, so in my webpage, it would return blank. By changing my code from sum(current_salary to COALESCE(sum(current_salary), 0), the issue was resolved.
When testing in PGAdmin, those GMs who I knew din't have any value in the "salary_retained" column, I would put a 0 for them in the calculations, so my query worked. Thanks to islemdev for making me rethink how the data I was using was being returned.

Conditionally Count a MYSQL Column Rows and Output Data via PHP

Sorry i am new to this. Just trying to learn. I am trying to conditionally count the number of times a particular condition occurs in SQL, using the case and count functions. This counts the number of males/females stored in eeg table. Here is my SQL query.
SELECT COUNT(CASE WHEN `Gender` = 'Male' THEN 1 END),
COUNT(CASE WHEN `Gender` = 'Female' THEN 1 END)
FROM `eeg`
This outputs the data when i run the query on the mysql backend (phpmyadmin), but in my php file, I get an "Undefined Index" error for those 2 rows. All othjer rows are perfectly okay. I do not know how to output those particular set of data to a variable.
Here is the SQL query (in full) in the php file:
$result = mysql_query("SELECT MONTH(ScanDate), YEAR(ScanDate),
COUNT(Investigation),
COUNT(CASE WHEN `Gender` = 'Male' THEN 1 END),
COUNT(CASE WHEN `Gender` = 'Female' THEN 1 END),
SUM(InvestigationAmount), SUM(AmountDue)
FROM eeg
WHERE Investigation = '{$investigation}'
AND ScanDate BETWEEN '{$ScanDate1}'
AND '{$ScanDate2}'");
Here is the while loop (in full):
while($row=mysql_fetch_array($result)){
$month_doe=$row['MONTH(ScanDate)'];
$year_doe=$row['YEAR(ScanDate)'];
$si=$row['COUNT(Investigation)'];
$male=$row["COUNT(CASE WHEN 'Gender' = 'Male' THEN 1 END)"];
$female=$row["COUNT(CASE WHEN 'Gender' = 'Female' THEN 1 END)"];
$sum_investigation=number_format($si);
$sia=$row['SUM(InvestigationAmount)'];
$sum_investigationamount=number_format($sia);
$srd=$row['SUM(AmountDue)'];
$sum_rebatedue=number_format($srd);
}
Thank you for your help. Been literally pulling my hair out, but love to learn and improve. And yes, mysql_query is depreciated :D
screenshots below:
Code screenshot
Use an alias for the expressions and use the alias to access the results of the expressions from php:
$result = mysql_query("SELECT MONTH(ScanDate) as sdyear,
YEAR(ScanDate) as sdmonth,
COUNT(Investigation) as investigation,
COUNT(CASE WHEN `Gender` = 'Male' THEN 1 END) as MaleCount,
COUNT(CASE WHEN `Gender` = 'Female' THEN 1 END) as FemaleCount,
SUM(InvestigationAmount) as investigationamount,
SUM(AmountDue) as amountdue
FROM eeg
WHERE Investigation = '{$investigation}'
AND ScanDate BETWEEN '{$ScanDate1}'
AND '{$ScanDate2}'");
while($row=mysql_fetch_array($result)){
$month_doe=$row['sdmonth'];
$year_doe=$row['sdyear'];
$si=$row['investigation'];
$male=$row["MaleCount"];
$female=$row["FemaleCount"];
$sum_investigation=number_format($si);
$sia=$row['investigationamount'];
$sum_investigationamount=number_format($sia);
$srd=$row['amountdue)'];
$sum_rebatedue=number_format($srd);
}
I would use this approach for every field that is an expression (the other sum() fields in the above query).

Laravel/Postgres db queries?

I have (weird) problem with query on Laravel/Postgres DB Queries. I will paste entire query here(it's little too long but we will focus on just one part of it):
select distinct "products".*, "brands"."name" as "brand", "brands"."image" as "brand_image", "product_categories"."name" as "category", "product_categories"."slug" as "category_slug", count(distinct product_features.feature_category_id) as features_count from "products" inner join "brands" on "products"."brand_id" = "brands"."id" inner join "product_categories" on "products"."category_id" = "product_categories"."id" left join "product_features" on "products"."id" = "product_features"."product_id" where "products"."deleted_at" is null and "products"."category_id" in (142) and "products"."published" = true and "brands"."published" = true and "product_categories"."published" = true and "product_categories"."deleted_at" is null and "price" >= 0 and "price" <= 19000 and "products"."brand_id" in (17) and
(product_features.feature_category_id = 555 and
CAST(product_features.value AS BOOLEAN) = true and
product_features.deleted_at IS NULL) or
(product_features.feature_category_id = 554 and
CAST(product_features.value AS BOOLEAN) = true and
product_features.deleted_at IS NULL) group by "products"."id", "brands"."name", "brands"."image", "product_categories"."name", "product_categories"."slug" having count(distinct product_features.feature_category_id) = 2 order by price asc
This is initial query but when I execute it I get weird error said:
ERROR: invalid input syntax for type boolean: "800"
I have no idea why is this error thrown?
Your product_features.value is a text field. While Postgres is OK casting all nonzero integers like 800 to boolean true, it is not OK with casting text like '800' to boolean.
Solution is to check product_features.value on emptiness and/or equality to '0' instead of CAST(product_features.value AS BOOLEAN) = true.

Validate mysql query if NULL

Is this query possible in mysql?
If query returns null, then set x = false else set x = true
Query
SET #s1 = (SELECT * FROM `wo_ticket_details_replay`
WHERE message NOT LIKE "[ SYSTEM%" AND `sv_number`='0715201569998')
CASE WHEN #s1 = NULL THEN
x = 'false'
ELSE
x = 'true'
END CASE;
You can use a subquery with EXISTS.

Mysql query option param

There is my query string, are there any problems about the bindParam?
$str = "select A.option_id,count(*) as sum
from tb_feedback A,tb_question B,tb_group C
where (A.question_id=B.id)
and (:question is null or B.id=:question)
and (B.group_num=C.id)
and (:group is null or C.name=:group)
and (:fromdate is null or A.date >= CAST(:fromdate AS DATE))
and (:todate is null or A.date <= CAST(:todate AS DATE))
group by A.option_id";
$sql = $this->conn->prepare($str);
$sql->bindParam(':question', $obj['question']);
$sql->bindParam(':group', $obj['group']);
$sql->bindParam(':fromdate', $obj['fromdate']);
$sql->bindParam(':todate', $obj['todate']);
I have found the reason that parameter's type not NULL, it is string, so it is not succeed when execute the next statement
(:question is null or B.id=:question)

Categories