简体   繁体   中英

PHP/SQL - Return boolean result from SQL query between two dates

I've been asked to build a scheduler to display special offers on a website based on start/end dates. Part of that is to conditionally display a link to the page if there is a valid offer in place. But I'm completely at a loss.

The following query fetches any current offers which fall within the correct dates:

$now = date('Y-m-j');
$sql = "SELECT * FROM sample WHERE date_from <= '".$now."' AND date_to > '".$now."'";

I've not been able to develop this query to return a TRUE/FALSE value (which I need for the existing navigational structure - created by another developer). There've been some posts stating to use EXISTS() or SELECT CASE WHEN EXISTS() on the existing query, followed by THEN/ELSE for the output. But after hours of trying to crack this I've only managed to garner errors.

I know it's probably possible to work around this, but I want to return a boolean from the SQL query itself.

case should work:

select
CASE 
  WHEN date_from <= '".$now."' AND date_to > '".$now."' THEN 'TRUE'
  ELSE 'FALSE'
END

from yourtable 

perhaps better

SELECT exists (
  SELECT * FROM sample WHERE date_from <= '".$now."' AND date_to > '".$now."') as BOO

BOO will be 1 if there is a match

PHP database queries return resources to the result of the query. The result is an array or object of elements returned by the select statement.

If you want to return a boolean from the sql query itself. Then you must change your * (asterisk) to something that is a boolean.

Depending on the database you are using, the exact syntax and functionality available changes. But let's assume microsoft sql or postgres..

Postgres:

$sql = "SELECT (count(*)>0) as bool_result FROM sample WHERE date_from <= '".$now."' AND date_to > '".$now."'";

Microsoft SQL:

$sql = "SELECT (case when count(*)>0 then 1 else 0 end) as int_result FROM sample WHERE date_from <= '".$now."' AND date_to > '".$now."'";

Microsoft SQL uses the tiny int or bit for booleans. So there is no way to return a strictly speaking "Boolean". Hence the case when structure for the 1 or 0 from the boolean comparison.

If you want to know if ANY rows are returned and you care not the result set, then maybe mssql_num_rows or pg_num_rows is more your answer. Both return the number of rows in the query result set. You could then compare that to being equal to 0 or 1.

This is about as close to an answer you can get without supplying a code example and more details.

Here's an example:

$sql = "SELECT * FROM sample WHERE date_from <= '".$now."' AND date_to > '".$now."'";
$res = pg_query($sql);
if( pg_num_rows($res) > 0 ) 
    ShowNav();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM