简体   繁体   中英

PHP Select Where Date Equals DateTime

I have a website where posts are recorded in a MySQL Table with an Added value, which is set to DateTime. An example of a stored value is 2016:12:12 15:30:21 .

So I now want to build a page which selects all records of a certain date, using a php script and URL paramater like added.php?date=2016-12-12 .

So my php script for this would be:

<?php
    if(isset($_GET["date"])){
        $date = $_GET["date"];
    } else {
        header("Location: $site_url");
        exit();
    };
?>

How do I now actually select the rows with this date? I'm trying to use:

$rows_sql = "SELECT id FROM posts WHERE added = '$date';

But this isn't working. Any ideas how I can get this working in the format I have?

您能否按以下方式更改查询行:

$rows_sql = "SELECT id FROM posts WHERE Date(added) = '$date';

There are few things that you need to be aware of:

Your code is vurenable to SQL Injection.

You need to provide date in proper format. To do so I suggest using DateTime::createFromFormat function or strtotime. Let's do it with simplier way (strtotime)

<?php 

$parsedDate = strtotime($_GET['date']);

if (false !== $parsedDate) {
    $date = date('Y-m-d H:i:s', strtotime($_GET);
    $rows_sql = "SELECT id FROM posts WHERE added = '$date'";
} else {
    die("date is in wrong format");
}

Basicly it checks whether string can be converted to timestamp strtotime function and if it is possible (NOT FALSE) it will convert it with the format that DB can handle YYYY-mm-dd hh:mm:ss

Often if you want to select from some time period then using operators like > < and BETWEEN may come handy. For example if you want to select the rows from whole day specified in GET date parameter

    if($date = strtotime($_GET['date'])) {
         $today = date('Y-m-d', $date);
         $rows_sql = "SELECT id FROM posts WHERE added BETWEEN '$today 00:00:00' AND '$today 23:59:59'";
    }

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