Home > Back-end >  Enter the date when the checkbox is selected
Enter the date when the checkbox is selected

Time:11-23

I'm trying to make it so that when the checkbox is selected it puts today's date in the database, I tried using timestamp but it puts it in all the spaces in the column, I'm a beginner in php The code I made was this:

<?php
            if (isset($_POST['Abate'])){
              $Abate="Sim";
              $data=time();
              $DiaAbate= date("Y/m/d", $data);
          }
          else{
              $Abate="Nao";
              $DiaAbate="";
          }
          ?>

CodePudding user response:

You have not included your table structure (CREATE TABLE statement) so I have assumed you have a DATE column for storing $DiaAbate. I have also assumed that the submitted date is in 22/11/2022 format. If you are using a different format for the POSTed date value, you will need to change the format string passed into DateTime::createFromFormat().

Your current code is vulnerable to SQL Injection as you are combining your static strings with user input without any validation. The simple example below uses a prepared statement for the insert query -

if (isset($_POST['Abate'])){
    $Abate = 'Sim';
    // create a date from the posted date string adn format it
    // see https://www.php.net/manual/en/datetime.createfromformat.php
    $DiaAbate = DateTime::createFromFormat('d/m/Y', $_POST['DiaAbate'])->format('Y-m-d');
} else {
    $Abate = 'Nao';
    $DiaAbate = null;
}

$query = 'INSERT INTO pc (Abate, DiaAbate) VALUES (?, ?)';
$query_run = mysqli_execute_query($con, $query, [$Abate, $DiaAbate]);

if ($query_run) {
    $_SESSION['status'] = 'Inserted Succesfully';
    header('Location: indexx.php');
} else {
    $_SESSION['status'] = 'Not Inserted';
    header('Location: indexx.php');
}
  • Related