MySQLi DATE_FORMAT not working at all

2019-09-18 14:08发布

问题:

I have the following code, the database column has got the date and time, I want to search for records using just the data part. I have the following but I have a feeling it is very wrong.

$query = "SELECT id,uid,product,jpgID,saledatetime FROM sales WHERE printed = ? AND DATE_FORMAT('?', 'y/m/d') AS saledatetime";

Edit: Working now, thanks:

if(login_check($mysqli) == true) {
    //logged in
    $session_date = $_SESSION['session_date'];

    $query = "SELECT id,uid,product,jpgID,saledatetime 
                FROM sales 
             WHERE printed = ? 
                AND DATE_FORMAT(saledatetime , '%y/%m/%d') = ?";
    if ($stmt = $mysqli->prepare($query)) {
        $printed = 0;
        $stmt->bind_param("is",$printed,$session_date);
        $stmt->execute();
        $stmt->store_result();

        //Get result
        $stmt->bind_result($result_id,$result_uid,$result_product,$result_jpgID,$result_saledatetime);

        //Number of rows returned
        $count_rows = $stmt->num_rows;
        echo $count_rows;
    }
} else {
    header("Location: index.php");  
}

回答1:

DATE_FORMAT has special syntax. Query didn't compare formatted datetime to anything, so I presume it was meant to be like this?

SELECT id, uid, product, jpgID, saledatetime 
  FROM sales
 WHERE printed = ?
   AND DATE_FORMAT(saledatetime, '%y/%m/%d') = DATE_FORMAT(?, '%y/%m/%d')