dongyan5641 2017-09-21 16:31
浏览 34

更正日期格式

I have a php form which contains fields for start date and end date. I have already stored the rows in my mysql database and I would like to display the records within the range of start and end dates. I have a column called tdate of datetime value. My form displays the start and end dates in mm/dd/yyyy but mysql doesn't accept that.

Updated:-

$edate = $_POST['edate'] ?? '';
$sdate = $_POST['sdate'] ?? '';
$endDate = date('Y-m-d', strtotime($edate));
$startDate = date('Y-m-d', strtotime($sdate));
if(isset($_POST['submit'])){
    $sql = "SELECT * FROM admin_master_tbl ";
$sql .= "WHERE tdate <= '$endDate' AND ";
$sql .= "tdate >= '$startDate' ";
$result = mysqli_query($conn, $sql);
$output = mysqli_fetch_array($result);
print_r($output); } 

Ok now it works on my form!

  • 写回答

2条回答 默认 最新

  • douqiangchuai7674 2017-09-21 16:45
    关注

    Use prepared statements and convert your date strings into a format which can be used by MySQL as dates. This answer is the MySQL centric one, which uses STR_TO_DATE to convert your mm/dd/yyyy strings into dates.

    $sql = "SELECT * FROM admin_master_tbl ";
    $sql .= "WHERE tdate <= STR_TO_DATE(?, '%m/%d/%Y') ";
    $sql .= " AND tdate >= STR_TO_DATE(?, '%m/%d/%Y')";
    $stmt = $con->prepare($sql);
    $stmt->bind_param("ss", $edate, $sdate);
    $stmt->execute();
    $stmt->close();
    

    The first parameter to bind_param(), namely "ss" tells PHP that we are binding two string parameters to the query.

    An alternative to STR_TO_DATE would be to convert your PHP date strings into an ISO format in PHP. In that case, you wouldn't need STR_TO_DATE, but using prepared statements would still be a good idea.

    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭