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

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.

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!

You can use strtotime to do your checking. No regex needed

$date = strtotime($_POST["date"]);
if($date === false) $dateErr = "Unrecognized Date format";
else $date = date('m/d/Y', $date); // Set your own date format here
if (preg_match("/^(19|20)\d\d[\-\/.](0*[1-9]|1[012])[\-\/.](0*[1-9]|[12][0-9]|3[01])$/", $date )){//This will match the input in format YYYY-MM-DD
//Date ok
}else{
//Invalid Date
}

Use the powerful DateTime class, DateTime::createFromFormat is useful here, it returns a new DateTime instance or FALSE on failure.

So it will go this way:

    if (empty($_POST["date"])) {
  $dateErr = "Date is required";
     } else {
       $format = 'Y-m-d'; // write your format here
       $date = DateTime::createFromFormat($format, $_POST["date"]);
       if($date)
       {
           // add to database
       }

Also your database field should be set as datetime which has the format Y-m-d, so before you insert it you have to format it to Y-m-d using PHP, like:

$date->format('Y-m-d');

That will return a proper string to insert in your database.