简体   繁体   中英

How write this mysql query?

I'm so stuck on this and would really appreciate any help. I have a form with some select options and I am trying to get it to query some date rows in my database for entries that meet tomorrow, next week and next month. I have gotten the mysql commands to work fine in php admin but I cant figure out how to get them to work within my form in php. I should add that the variables selected get put into an array, and I just can't figure out where and how to write the MYSQL query.

The mysql commands I want to use are:

**NEXT WEEK**
SELECT start FROM  `tablename` 
WHERE START = DATE_ADD( CURDATE( ) , INTERVAL( 9 - IF( DAYOFWEEK( CURDATE( ) ) =1, 8, DAYOFWEEK( CURDATE( ) ) ) ) DAY ) 

**NEXT MONTH**
SELECT start FROM `tablename` WHERE start BETWEEN DATE_SUB(LAST_DAY(DATE_ADD(NOW(), INTERVAL 1 MONTH)),INTERVAL DAY(LAST_DAY(DATE_ADD(NOW(), INTERVAL 1 MONTH)))-1 DAY) AND LAST_DAY(DATE_ADD(NOW(), INTERVAL 1 MONTH))

Here is the form:

<select id="start" name="start" class="form-control">
<option value="" disabled selected>When</option>
<option value="<?php echo date("Y-m-d");?>">Today</option>
<option value="<?php ------what goes here?---------?>">Tomorrow</option>
<option value="<?php-----what goes here?-----------?>">Next Month</option>
</select>

Here is the problem code:

$whereClauses = array(); 
if (! empty($_GET['start'])) $whereClauses[] ="(start='".mysqli_real_escape_string($connection,$_GET['start'])."'";

I'd suggest you don't put dates or long strings as your values to your select form. It's just going to become frustrating to debug. Instead, use a simple key such as:

<select id="start" name="start" class="form-control">
<option value="" disabled selected>When</option>
<option value="today">Today</option>
<option value="tomorrow">Tomorrow</option>
<option value="next_month">Next Month</option>
</select>

And now, you can simple do in your PHP:

$whereClauses = array(); 
if (!empty($_GET['start']))
    if ($_GET['start'] == "today") {
        $whereClause[] = "START = CURDATE()";
    }
    else if ($_GET['start'] == "tomorrow") {
        $whereClause[] = "START = DATE_ADD( CURDATE( ) , INTERVAL( 9 - IF( DAYOFWEEK( CURDATE( ) ) =1, 8, DAYOFWEEK( CURDATE( ) ) ) ) DAY )";   
    }
    else if ($_GET['start'] == "next_month") {
        $whereClause[] = "start BETWEEN DATE_SUB(LAST_DAY(DATE_ADD(NOW(), INTERVAL 1 MONTH)),INTERVAL DAY(LAST_DAY(DATE_ADD(NOW(), INTERVAL 1 MONTH)))-1 DAY) AND LAST_DAY(DATE_ADD(NOW(), INTERVAL 1 MONTH))";
    }

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