php insert date into mysql – Convert the date using date format. Insert the date in the database using a Insert MySQL query.
php insert date into mysql – PHP code for inserting data into database from form using mysqli
Lets get started to: (php insert date into mysql)
Step 1: Create a table:
Make a DB table named shops into your Database (MySQL) as follows
CREATE TABLE `shops` ( `id` int(11) NOT NULL, `name` varchar(191) NOT NULL, `created_date` DATE NOT NULL );
Step 2: Create a PHP file
index.php
simply copy and paste the below html form design source code:
<?php session_start();?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>php insert date into mysql - itsolutionstuck.com</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <?php if(isset($_SESSION['status'])) { ?> <div class="alert alert-warning alert-dismissible fade show" role="alert"> <strong>Hey!</strong> <?php echo $_SESSION['status']; ?> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> <?php unset($_SESSION['status']); } ?> <div class="card mt-5"> <div class="card-header"> <h4>How to Insert Date Values into Database in php - www.itsolutionstuck.com</h4> </div> <div class="card-body"> <form action="code.php" method="POST"> <div class="form-group mb-3"> <label for="">Name</label> <input type="text" name="name" class="form-control" /> </div> <div class="form-group mb-3"> <label for="">Date of Birth</label> <input type="date" name="created_date" class="form-control" /> </div> <div class="form-group mb-3"> <button type="submit" name="updated_at" class="btn btn-primary">Save Data</button> </div> </form> </div> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> </body> </html>
Step 3: Create a code.php file
code.php
simply copy paste the below source code to insert date value in mysql database in php.
<?php session_start(); $con = mysqli_connect("localhost","root","","phptutorials"); if(isset($_POST['updated_at'])) { $name = $_POST['name']; $created_date = date('Y-m-d', strtotime($_POST['created_date'])); $query = "INSERT INTO shops (name,created_date) VALUES ('$name','$created_date')"; $query_run = mysqli_query($con, $query); if($query_run) { $_SESSION['status'] = "Date values Inserted"; header("Location: index.php"); } else { $_SESSION['status'] = "Date values Inserting Failed"; header("Location: index.php"); } } ?>