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);
?>
1
  • 1
    You could use strtotime function, but the main problem is that you're using text to insert time. I'd change that if I were you. Commented Oct 11, 2014 at 16:34

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

thanks for the help. It worked as expected. I am just a beginner in programming, thanks for the support and advice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.