How to insert dates into a database table using PHP?

Asked

Viewed 1,261 times

1

I am creating a form where I need to save the dates that are placed inside the Inputs in a table of the Mysql database, but as I am now apprehending PHP, I am having difficulties, because with the code I have every time I press to send the information the data field is reset 0000-00-00 after registration.

I need a PHP code to link the date information, to name and E-mail already can save normally.

Example of what I’m using:

<html>
<head>
<Title>Exemplo</Title>
</head>
<body>
    <form action="Conecta.php" methodh="POST">
        Nome<input type="text" name="nome"/>
        E-mail<input type="email" name="email"/>
        Data de nascimento<input type="text" name="data_nasc"/>
        <input type="submit" name="Enviar"/>
    </form>
</body>
</html>

This is the PHP code I’m using, but only saves name and email....

<?php
$servername = "localhost";
$database = "Cadastro";
$username = "Root";
$password = "xxxxx";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";

// RECEBENDO OS DADOS PREENCHIDOS DO FORMULÁRIO !

$nome = $_POST ["nome"]; 
$email = $_POST ["email"]; 
$data_nasc = $_POST ["data_nasc"]; 
$data = date("Y-m-d",strtotime(str_replace('/','-',$data)));  

$newslleter = "INSERT INTO newslleter (nome,email,data_nasc) VALUES ('$nome','$email','$data_nasc')";

if (mysqli_query($conn, $newslleter)) {
      echo "New record created successfully";
} else {
      echo "Error: " . $usuarios . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

1 answer

0


Simple lack of attention friend, but just you fix here $data = date("Y-m-d",strtotime(str_replace('/','-',$data_nasc))); and at the time of inserting you enter the $data variable, instead of $data_nasc in the query. $newslleter = "INSERT INTO newslleter (nome,email,data_nasc) VALUES ('$nome','$email','$data')";

  • I made the correction and I was able to save the date values but only putting in the <input/> format Y-m-d ex:(2018/05/27), what would be the procedure for me to put in the <input> the format d-m-Y and write in the Y-m-d ? Thank you

  • SELECT DATE_FORMAT(data_nasc, '%d/%m/%Y'); this returns its date in d-m-Y format

  • It could be more specific, I need to receive the date of the input coming in the format Day/Month/Year and pass to the code I have --> $name = $_POST ["name"]; $email = $_POST ["email"]; $data = $_POST ["date"]; $data = date("Y-m-d",strtotime(str_replace('/','-',$data)); $newslleter = "INSERT INTO newslleter (name,email,date) VALUES ('$name','$email','$data')";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.