P
P
primitiv2022-03-24 21:19:34
PHP
primitiv, 2022-03-24 21:19:34

How to write a SQL SELECT PDO PHP query to get data for two rows?

I'm trying to implement getting data from the database in two lines

SELECT * FROM `table_products` WHERE `product_type` = :product_type AND `product_group` = :product_group

However, it happens that the second variable is empty and then the query for the selection breaks (the database does not return anything), how to implement an sql query so that if there is one variable with data for the selection, search for it, and if there is data for the selection in the second variable, then get data on both of them. I used the logical "AND", and I understand that the problem may be in it, but I will say right away, "OR" does not suit me, since if both variables have data for sampling, they should both be used, if only in one then the second the variable should be discarded (not taken into account) when fetching data. Thanks and sorry for the tautologies

Answer the question

In order to leave comments, you need to log in

4 answer(s)
F
FanatPHP, 2022-03-24
@FanatPHP

Two ways https://phpdelusions.net/pdo_examples/dynamical_where

T
ThunderCat, 2022-03-24
@ThunderCat

I'm trying to implement getting data from the database in two lines
Not by rows, but by columns, they usually say "by fields". The most obvious and simple solution is to check for the presence of a variable and accordingly add the required field "manually" by concatenating query strings.

P
primitiv, 2022-03-24
@primitiv

Sadly, as I understand it, SQL is poor here, and you have to fence a cloud of lines of php code, but I was hoping!

R
rPman, 2022-03-25
@rPman

since it is not said what kind of logic in the request should be with zero values, I chose the option in the example - and zeros in the database too.

select .. from ... where ... and (:product_group is null and `product_group` is null) or (`product_group` = :product_group)

to use the same parameter in the request several times, use user variables (live until the end of the session), i.e. you execute two queries, the first one
set @product_group=:product_group
and in the query itself instead of :product_group you use @product_group

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question