2

I have a php page when get the values from $_GET variables and put this in a php query with two condition:

AND book_id = '$bookid"
AND book_date between coalesce('$bookdate',book_date) AND coalesce('$bookdate',book_date)

The problem is this condition: AND book_date between coalesce('$bookdate',book_date) AND coalesce('$bookdate',book_date) To work, the query want '$bookdate' = null, and when retrieve the variables, set the value as a string.

How to make this?

Thanks

Frankie
  • 490
  • 8
  • 23
  • What have you tried so far? Where are you stuck? If this is really part of a database query, be warned that it is widely open for SQL injection. To avoid getting hacked, use prepared statements – Nico Haase Aug 25 '22 at 08:36

3 Answers3

4

You can use the Elvis operator:

$bookdate = $_GET['bookdate'] ?: null;

More information here: https://stackoverflow.com/a/1993455/12750122

Skully
  • 2,882
  • 3
  • 20
  • 31
Ovinz
  • 453
  • 5
  • 11
0

It seems you will just to need to conditionally declare your variable before use in the query.

$bookdate = !strlen($bookdate) ? null : $bookdate

Or perhaps more appropriately from $_GET...

$bookdate = empty($_GET['bookdate']) ? null : $bookdate

...because your variable name insinuates a date-type value, I will assume that a 0 value will not be passed or would not be valid for your use case. I say this because empty() evaluates 0 as true.

*Superglobal elements should be checked for existence before you try to access/manipulate them to avoid receiving Notices. (e.g. isset() or empty() or array_key_exists())

Ultimately, you should not be directly injecting variables into your query. You should be using a prepared statement and binding your variables to placeholders.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
-1

check the variable before you make your sql query:

$bookdate = !empty($bookdate) ? $bookdate : null;

Sysix
  • 1,572
  • 1
  • 16
  • 23