0

why can't I save the current date in my database on mysql, all columns here enter except the date which only displays 0000-00-00 in the database

<?php
require_once 'koneksi.php';

if (isset($_POST['submit'])) {
    foreach ($_POST['keterangan'] as $id => $keterangan) {
        $nama_siswa = $_POST['nama_siswa'][$id];
        $kelas = $_POST['kelas'][$id];
        $peminatan = $_POST['peminatan'][$id];
        $waktu = date("Y-m-d H:i:s");

        $sql = "INSERT INTO kehadiran VALUES ('','$nama_siswa', '$kelas', '$peminatan', '$keterangan', $waktu  )";
        $result = mysqli_query($conn, $sql);

if ($result) {
            header("location:index.php?page=home.php"); 
        } else {
            echo "failed data added";
        }
  }
}


?>

Today's date column is not successful in entering, displaying data according to the image

aynber
  • 22,380
  • 8
  • 50
  • 63
  • 3
    Date columns must be quoted. Or you can use [prepared statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [bind_param](http://php.net/manual/en/mysqli-stmt.bind-param.php) to prevent all quoting issues. Another way to bypass it would be to use the mysql function `CURDATE()` instead of creating the date with PHP. – aynber Jul 02 '19 at 20:20
  • where to put mysql function CURDATE() in the code? – dhanis alghifari Jul 02 '19 at 20:30
  • In place of `$waktu` in your query. `'$keterangan', CURDATE() )";` – aynber Jul 02 '19 at 20:34
  • https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Charlotte Dunois Jul 02 '19 at 20:38
  • thanks !!! the problem is solved. – dhanis alghifari Jul 02 '19 at 20:39
  • Possible duplicate of [When to use single quotes, double quotes, and backticks in MySQL](https://stackoverflow.com/questions/11321491/when-to-use-single-quotes-double-quotes-and-backticks-in-mysql) – aynber Jul 02 '19 at 20:40
  • Possible duplicate of [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Dharman Jul 02 '19 at 21:52

2 Answers2

1

From an initial look, it seems you forgot to enclose your variable $waktu with single quote, as in Mysql datetime values should be enclosed by quotes similar to string values. so the query should be updated as following:

$sql = "INSERT INTO kehadiran VALUES ('','$nama_siswa', '$kelas', '$peminatan', '$keterangan', '$waktu'  )"
0

You should put CURDATE() function in the code replacing

$waktu

Luiz
  • 141
  • 2
  • 14