Skip to content
Advertisement

Post date format and select date format from the database

I have a textbox that displays the current date in format: d-m-Y

<input type="text" name="date" class="form-control" value="<?php echo date('d-m-Y');?>"/>

When I save this the date will written to my database like: Y-m-d. For example: the current date is: 02-06-2016. My script writes this to the database as: 2002-06-16.

I am using the following code to save the data to my database:

<?php
 session_start(); 

 $correct = true;

 $date = $_POST['date'] ;

 if($correct){
  $db = new PDO('mysql:host=localhost;dbname=db', 'root', '');

  $query = "INSERT INTO table(date) VALUES (?)";
  $stmt = $db->prepare($query);
  $stmt->execute(array($date));

  header('Location: ./index.php');  
 }
 else
 {
  echo "Error";
 }
?>

What do I need to change in my code so it will post it like: 2016-06-02 Y-m-d or 02-06-2016 d-m-Y?

If d-m-Y is not possible, how can show the data that is written like Y-m-d in the database show as format d-m-Y in my php script?

Edit:

For selecting the date I use:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM table WHERE id='1' ORDER BY id DESC LIMIT 1";

$sql = date("d-m-Y",strtotime($row['date']));

$result = $conn->query($sql);

if ($result->num_rows > 0) {

     // output data of each row
     while($row = $result->fetch_assoc()) {
                      echo "<td>" . $row["id"]. "</td>";
                      echo "<td>" . $row["date"]. "</td>";
     }                   
} else {
                      echo "<p> </p>";
}

$conn->close();

?>  

Advertisement

Answer

$date = $_POST['date'] ;

$date = date("Y-m-d",strtotime($date));

To show date in d-m-Y format in HTML page, again convert it into

$date = date("d-m-Y",strtotime($row['date']));

[Note: I’m assuming your fetch array as $row and column as date.]

For more info, please have a look on strtotime – php manual

Update Code (As question is edited)

$sql = "SELECT * FROM table WHERE id='1' ORDER BY id DESC LIMIT 1";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo "<td>" . $row["id"]. "</td>";
    echo "<td>" . date("d-m-Y",strtotime($row['date'])). "</td>";
  }                   
} else {
  echo "<p> </p>";
}

$conn->close();
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement