Laravel/Postgres db queries? - php

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.

Related

SQL Server query on 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.

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.

Query works in workbench but not in php

I'm trying to assign a variable a value based on a subquery in the where statement. The problem is that it doesn't work in php but in the workbench the query runs fine. I don't get any errors in php and it returns the correct pay ids but the variable field returns empty.
SELECT pay_id, #available AS amount_available
FROM tblpayments payments
WHERE customer_id = 9
AND (
#available := (pay_amount - (
SELECT if(sum(applied_amount) IS NULL, 0, sum(applied_amount))
FROM tblxref_pmt_chg xref WHERE xref_pay_id = payments.pay_id
))
) > 0
Why not try using a JOIN instead of a subquery/variable?
Something like this:
SELECT pay_id, (pay_amount - COALESCE(SUM(applied_amount), 0)) AS amount_available
FROM tblpayments payments
LEFT JOIN tblxref_pmt_chg xref ON xref_pay_id = payments.pay_id
WHERE customer_id = 9
GROUP BY payments.pay_id
HAVING amount_available > 0

Error handling in the following sql query

Fiddle with tables here
I'm using the following sql with the tables in the fiddle to check if a user has reached the borrowing limit. The problem here is, If an invalid item number were supplied it returns NULL, if a user has not borrowed any items, it returns NULL. This way, I cannot tell if a invalid item number were supplied or if a user actually has not borrowed any books. What would be a good way to check if a invalid item number was supplied or a member actually has not borrowed anything under that category?
set #mId = 3 //Has not borrowed anything till now.
set #id = 21; //This item does not appear in the collection_db table and is therefore invalid.
set #country = 'US';
SELECT col1.id, col1.holder, col2.borrowMax maxLimit, count(lend.borrowedId) as `count`
FROM collection_db col1
INNER JOIN collection_db col2
ON col1.holder = col2.id
INNER JOIN lendings lend
ON col1.holder = lend.holder and col1.country = lend.country
WHERE col1.id = #id and col1.country = #country
AND col2.category = 10
AND lend.memId = #mId and lend.country = #country
The furthest I could get with the one query is (had to take out php and "country" vars for fiddle to work):
SELECT col1.id, col1.holder, col2.borrowMax maxLimit, count(lend.borrowedId) as `count`
,case when valid1.id is not null then 'true' else 'false' end as validId
FROM collection_db col1
INNER JOIN collection_db col2
ON col1.holder = col2.id
INNER JOIN lendings lend
ON col1.holder = lend.holder,(
Select Distinct a.id From collection_db a
Where a.id = 4) valid1
WHERE col1.id = 4
AND col2.category = 10
AND lend.memId = 1
You may have to do a preparatory query checking for a valid memId:
$theQuery = "SELECT DISTINCT memId FROM lendings WHERE memId = 1"
Then test it here:
if (mysql_num_rows(mysql_query($theQuery)) <= 0) { /* No memId exists */ }
else { /* Do big query here */ }
You can use a tableA LEFT JOIN tableB, which will return results for the tableA even if tableB has no matches and will return NULL values for those in tableB.
Unfortunately, I can't quite figure out where you need LEFT JOINS, but probably you want them in both places.
You also might have to reorder the tables if it is the first table that should be on the right side of a LEFT JOIN. You could use a RIGHT JOIN but it is less readable to me.
maybe you should try "left join" if col1 do not have too much data,or do the query step by step

MySQL error code needed

MySQL always sends a "default response" even when the data doesn't match the query!
How can I design my query to get an error code from MySQL if no data is matching the query?
I need an error code from MySQL to create a 404 or 410 page.
SELECT
place.ID AS id,
place.latitude AS lat,
place.longitude AS lng,
IF(
place.translationID IS NULL,
place.name,
placel10n.text
) AS cityname,
IF(
admcode.translationID IS NULL,
'',
statel10n.text
) AS statename,
IF (
countrycode.translationID IS NULL,
countrycode.name,
countryl10n.Text
) AS countryname,
IF(
place.textID IS NULL,
'',
`l10n-strings`.text
) AS description
FROM
places AS place
LEFT JOIN `l10n-strings` AS placel10n ON (place.translationID = placel10n.translationID AND placel10n.languageCode = 'de')
LEFT JOIN admin1codesascii AS admcode ON (place.admin1 = admcode.statecode AND place.country = admcode.country)
LEFT JOIN `l10n-strings` AS statel10n ON (admcode.translationID = statel10n.translationID AND statel10n.languageCode = 'de')
LEFT JOIN countries AS countrycode ON (place.country = countrycode.iso_alpha2)
LEFT JOIN `l10n-strings` AS countryl10n ON (countrycode.translationID = countryl10n.TranslationID AND countryl10n.LanguageCode = 'de')
LEFT JOIN texts ON (place.textID = texts.id)
LEFT JOIN `l10n-strings` ON (texts.translationID = `l10n-strings`.translationID AND `l10n-strings`.languageCode= 'de')
WHERE
place.id = '8'
AND
place.featurecode = 'A'
OR
place.featurecode = 'AB'
OR
place.featurecode = 'AAC'
LIMIT 0,1
This query always returns a result even when the where statements are wrong.
Yes, that's the way SQL works. If there are no rows that match your query, the result set will be empty. It's the job of the program (written in PHP or what have you) in which your SQL query is embedded to respond to the "no rows" case and change the response status (to 404 or what have you). SQL queries are not responsible for HTTP status codes -- it's chalk and cheese.
In MySQL, AND has higher operator precedence than OR, so the conditions in your WHERE clause will be interpreted as
(place.id = '8' AND place.featurecode = 'A') OR
place.featurecode = 'AB' OR
place.featurecode = 'AAC'
Use parentheses to be explicit about the order of operation you intend. Perhaps you meant this?
place.id = '8' AND
(place.featurecode = 'A' OR
place.featurecode = 'AB' OR
place.featurecode = 'AAC')

Categories