0

hi guys can i insert this

date_default_timezone_set(Asia/Hong_Kong);
$date = date('"m/d/Y H:i:s"');

instead of

"INSERT INTO date_time(`submitted_time`) VALUES (NOW())"

because my problem is using NOW() or CURRENT_TIMESTAMP() gives me a inaccurate time

im doing this but when i look at the database this is what is been inserted 0000-00-00 00:00:00.0

date_default_timezone_set('Asia/Manila');

if(isset($_POST['submit'])) {
    $date = date('"m/d/Y H:i:s"');
        $query = "INSERT INTO `date_time`(`submitted_time`)
                    VALUES('$date')";
        if($conn->query($query)) {
            echo "success";
        } else {
            echo "error";
        }
}
JustAngelo
  • 29
  • 9

1 Answers1

0

If you actually want to insert a datetime that you generate this is how it is done.

NOTE: The format of a date must be Y-m-d H:i:s as that is the format MYSQL understands for its DateTime data type

date_default_timezone_set('Asia/Manila');

if(isset($_POST['submit'])) {

    $query = "INSERT INTO `date_time` (`submitted_time`) VALUES(?)";
    $stmt = $conn->prepare($query);

    // note the DateTime must be in this format to store correctly on a MYSQL database
    $dt = date('Y-m-d H:i:s');

    $stmt->bind_param('s', $dt);
    $status = $stmt->execute();

    if(!$status) {
        echo $stmt->error;    
        exit;
    }
    echo "success";
}

If you want to view, show your users a DateTime in any other format that is the job of the presentation layer to reformat it to whichever locale specific format.

Your script was at risk of SQL Injection Attack Have a look at what happened to Little Bobby Tables Even if you are escaping inputs, its not safe! Use prepared parameterized statements

Community
  • 1
  • 1
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149