O
O
Optimus2014-11-13 12:06:32
MySQL
Optimus, 2014-11-13 12:06:32

How to make a query to the database?

There are search parameters in GET for a database request:
search.php?lic=0&section=1,2&type=1,2,3,4
One of the 3 parameters will be mandatory, but any other two may not be. How to query the database?
For example I do this:

SELECT `id`
FROM `content`
WHERE lic='".$lic."' AND section='".$section."' AND type='".$type."'

But if one of the lic or section or type variables is empty, will the query work with an empty condition?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rsa97, 2014-11-13
Pyan @marrk2

What are variables equal to if they are not present in the query? If the value is an empty string, then you can write it like this:

$req = $mysqli->prepare(
    "SELECT `id` FROM `content` ".
        "WHERE ('' = ? OR `lic` = ?) ".
            "AND ('' = ? OR `selection` = ?) ".
            "AND ('' = ? OR `type` = ?)"
);
$req->bind_param('ssssss', $lic, $lic, $selection, $selection, $type, $type);

A
Alexey, 2014-11-13
@Pentblch

Instead of AND, write OR and try.

K
KOPC1886, 2014-11-13
@KOPC1886

In addition to the answers above, do not only check, but also intval functions - if you're expecting a number, strip_tags. Better yet, use PDO.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question