doushi1974 2014-08-03 22:25
浏览 28
已采纳

如何阻止将无效日期发送到数据库

I require a date to be entered in the correct format, and if it isn't then an error is shown. My PHP program looks like this:

    if (empty($_POST["date"])) {
      $dateErr = "Date is required";
         } else {
           $date = test_input($_POST["date"]); etc

This is just the standard way of showing error for an improper date format. But my problem is that even though an error is shown, there is nothing that is stopping that date (in the wrong format) from being passed into the database. When I check my database, I see that date and it is not what I want. Is there a way that a date written in the wrong format can be blocked from ending up on my database? Like a filter, I mean.

  • 写回答

4条回答 默认 最新

  • douweilei2307 2014-08-03 22:30
    关注

    You should use a function to check whether the date given is in the appropriate format before you begin your db transaction. You can do this in the following approach using regular expressions as @Subhanker mentioned to match to the following format YYYY-MM-DD:

     if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $_POST['date']))
    {
        //Start DB transaction here
    
        // Create connection
          $con=mysqli_connect("example.com","peter","abc123","my_db");
    
        // Check connection
          if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
          }
    
        // escape variables for security
         $form_date = mysqli_real_escape_string($con, $_POST['date']);
    
    
         $sql="INSERT INTO dates_table (dates)
               VALUES ('$form_date')";
    
         if (!mysqli_query($con,$sql)) {
          die('Error: ' . mysqli_error($con));
          }
    
         echo "1 record added";
    
    }else{
        $dateErr = "Date is required";
    }
    

    Please let me know if you have any questions!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?