0

I am trying to insert data from a html input form to mysql database. In my html form the input type is 'text' and my mysql data base type is 'date'. while trying to insert data to respective field in my sql, inserting null value only. please help. my html script and php/mysql insert script is attaching.

html

<div class="form-group">
<div class="input-group col-sm-4">
  <div class="input-group-addon">Payment Due Date&nbsp;&nbsp;<i class="fa fa-calendar-o"></i></div>
  <input id ="duedt" class="form-control"  type="text" name ="due_date" required/>
</div>

php mysql code

        <?php
$con=mysqli_connect("localhost","root","pra@181178","ayrilmana");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
$sql= "INSERT INTO dlbcc_purchase (purch_date, purch_amt, purch_dtls,due_date)
VALUES
('$_POST[purch_date]','$_POST[purch_amt]','$_POST[purch_dtls]','$_POST[due_date]')";

if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }

//echo "1 record added";
Header( "Location: purchase.php" );

mysqli_close($con);
?>
Prajith A S
  • 457
  • 3
  • 8
  • 23
  • 1
    You could use [strtotime](http://php.net/manual/en/function.strtotime.php) function, but the main problem is that you're using text to insert time. I'd change that if I were you. – Andrei P. Oct 11 '14 at 16:34

2 Answers2

1

In my site I have datas like you. I insert them in database using input type = "data" and I haven't problems. The insert query put the value of the choosen data without mistakes ^^. Using type="data" you'll see a little calendar if you click on the input.

JEricaM
  • 794
  • 2
  • 15
  • 37
0

Something like this should work:

<?php
//Open MySQL onnection

$sql = "INSERT INTO dlbcc_purchase (purch_date, purch_amt, purch_dtls, due_date) VALUES ('"  . $_POST['purch_date'] . "', '" .$_POST['purch_amt'] . "','" . $_POST['purch_dtls'] . "','" . date('Y-m-d', strtotime($_POST['due_date'])) . "')";

if (!mysqli_query($con, $sql)) {
    die('Error: ' . mysqli_error($con));
}

//close MySQL connection and other code
?> 

Please be aware of some things:

  • You're vulnerable for MySQL injections. See How can I prevent SQL-injection in PHP?.
  • Improve your error handling, not with die() or exit().
  • The date could be wrong or null, since PHP is "trying" to convert it to a Unix Timestamp, and then convert it back to a MySQL date format.
  • The best thing is to use a type "date" in your HTML form (since HTML5) or a datepicker (recommended!) for this.
Community
  • 1
  • 1
Wouter0100
  • 430
  • 6
  • 19
  • thanks for the help. It worked as expected. I am just a beginner in programming, thanks for the support and advice. – Prajith A S Oct 11 '14 at 17:48