Date of birth insertion insertion in mysql through php.

I am having a problem while inserting the Date of Birth field's value from html form to mysql datebase using the php. I have used the input type 'date' in html to get the input.
<?php
       $DOB=$_POST['DOB'];
      $DOB = explode("/",$DOB);
      $DOB = "$DOB[2]-$DOB[0]-$DOB[1]";
      $sql = "INSERT INTO signin (F_name,U_name,password,email,DOB,phn)VALUES ('$F_name','$U_name','$password','$email','$DOB','$phn')";
?>
<html
DOB:<input type="date" name="DOB" size="20"><br><br>
/html>

output error:
( ! ) Notice: Undefined offset: 2 in C:\wamp64\www\Blogger\signin.php on line 20
Call Stack
#      Time      Memory      Function      Location
1      0.0004      248128      {main}( )      ...\signin.php:0

( ! ) Notice: Undefined offset: 1 in C:\wamp64\www\Blogger\signin.php on line 20
Call Stack
#      Time      Memory      Function      Location
1      0.0004      248128      {main}( )      ...\signin.php:0
Error: INSERT INTO signin (F_name,U_name,password,email,DOB,phn)VALUES ('kkkk','qqqqq','77777','mmmmmmmmm','/2017-03-24/','10000000')
Incorrect date value: '/2017-03-24/' for column 'DOB' at row 1
Souvik MisrastudentAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Nitin SontakkeDeveloperCommented:
Just stating a problem statement isn't quite useful, is it? Post some values, post the sql is being used / issued, share some data / error received, etc.

All I can guess is you are not passing the date in correct format. Format used should be yyyy-MM-dd.
1
mohan singhWeb developerCommented:
You are concatenating your date is worng

what you are doing see below
<?php
 $DOB=$_POST['DOB'];
      $DOB = explode("/",$DOB);
      $DOB = "$DOB[2]-$DOB[0]-$DOB[1]";
This is wrong method 
?>

Open in new window

Do like This
<?php
  $DOB=$_POST['DOB'];
      $DOB = explode("/",$DOB); 
      $DOB = $DOB[2]."-".$DOB[0]."-".$DOB[1];
This is correct way to change your / to - 
?>

Open in new window

Thank You
Mohan Singh
1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Julian HansenCommented:
There is nothing wrong with
$DOB = "$DOB[2]-$DOB[0]-$DOB[1]";

Open in new window

This is perfectly legal - the only change I would make is to put the array values in { }
$DOB = "{$DOB[2]}-{$DOB[0]}-{$DOB[1]}";

Open in new window

This is arguably better than concatenation which makes for far messier code.

If your date is in MM / DD / YYYY format then to convert it you can use the date() and strtotime() functions
$DOB = date('Y-m-d', strtotime($inputDate));

Open in new window

Where $inputDate is your MM/DD/YYYY value from your post. To use it in your code you can do this
// FIRST NEVER ASSUME YOUR POST DATA IS VALID OR EXISTS
$inputDate = isset($_POST['DOB']) ? $_POST['DOB'] : false;

// ASSUMES THE OTHER FIELDS $password, $F_name ETC ARE RETRIEVED BEFORE QUERY

// IF DATE IS PRESENT THEN PROCEED
if ($inputDate) {
  $DOB = date('Y-m-d', strtotime($inputDate));
  $sql = <<< QUERY
INSERT INTO signin (
  F_name,
  U_name,
  password,
  email,
  DOB,
  phn
)
VALUES (
  '{$F_name}',
  '{$U_name}',
  '{$password}',
  '{$email}',
  '{$DOB}',
  '{$phn}'
)
QUERY;  
}

Open in new window

Note in the above I have used HEREDOC notation for the query - this makes formatting of large text blocks easier as it allows for double and single quotes as well as variable insertion.
Note also the use of the { } around the variable names - these are optional, usually used to remove ambiguity from variables embedded in strings - but I use them by default.

I would also consider using a prepared statement for the above.

Let's look at your error though. Something does not make sense - you have obviously not posted all your code - as the error references line 20 which is not useful to us as you have posted only 4 lines of code.

If the script was bugging out with this in the Query "/2017-03-24/" - then we would need to see what the RAW POST is coming in because that value does not look like it could have been created with the code you have.

I am unable to repeat the result you are getting.

Suggestion
1. Post your full source
2. On line 1 of your script (after the <?php) put this code
echo "<pre>" . print_r($_POST, true) . "</pre>";

Open in new window

And post that output here.
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Chris StanyonWebDevCommented:
Pretty sure the value of a Date field is always in the format of yyyy-mm-dd when it's POSTed. You're trying to explode that value on the slash - explode("/",$DOB). Because the value has no slashes, you will only ever end up with 1 entry in your DOB array:  $DOB[0] = 'yyyy-mm-dd'

That's the reason you're getting the Undefined Offset errors. $DOB[1] and $DOB[2] don't exist!

Because the Date is passed in a standard way, you're better off using the built-in date functions:

$dob = new DateTime($_POST['DOB']);
$formattedDoB = $dob->format("y-m-d"); // set your format here to whatever you need.

Then insert the $formattedDoB into your Query.
0
Henry KorirSoftware EngineerCommented:
Post the
signin.php 

Open in new window

and
.sql

Open in new window

file. The information you posted is not enough to guarantee a solution.
0
Souvik MisrastudentAuthor Commented:
here ,is the whole code


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

 $conn = mysqli_connect($servername, $username, $password, $dbname);

 if (!$conn) {
     die("Connection failed: " . mysqli_connect_error());
 }
	if($_POST){
	$F_name=$_POST['Full_name'];
	$U_name=$_POST['User_Name'];
	$password=$_POST['password'];
	$email=$_POST['e-mail'];
	$phn=$_POST['mobileno'];
	$DOB=$_POST['DOB'];
	$DOB = explode("/",$DOB);
	 $DOB = "{$DOB[2]}-{$DOB[0]}-{$DOB[1]}";
	 	 $sql = "INSERT INTO signin (F_name,U_name,password,email,DOB,phn)VALUES ('$F_name','$U_name','$password','$email','$DOB','$phn')";
	if (mysqli_query($conn, $sql)) {
	    echo "New record created successfully";
	} else {
	    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
	}
	mysqli_close($conn);
	}
?>


<html>
<body>
<head>
</head>
<title>Blogger's Arena</title>
<link href="themes/1/js-image-slider.css" rel="stylesheet" type="text/css" />
    <script src="themes/1/js-image-slider.js" type="text/javascript"></script>
    <link href="generic.css" rel="stylesheet" type="text/css" />
</head>
<body style="background-image:url(images/Blurred-Background-Sunset-3c-Free.jpg)">
<h1 style="background-color:green;text-align:center;color:red;">Welcome to Blogger's Arena</h1>
    <div id="sliderFrame">
        <div id="slider">
		
                <img src="images/blogging_image.jpg"/>
            </a>
			
            <img src="images/blog-793047_960_720.jpg"/>
            <img src="images/download.jpg"/>
            <img src="images/to-blog.jpg"/>
            <img src="images/i-think.jpg"/>
       
	   </div>
        <div id="htmlcaption" style="display: none;">
            
        </div>
    </div>

    <div class="div2">
       
    </div>
<p style="color:LightCoral;text-align:center;font-size: 150%;font-family: "Times New Roman", Times, serif;"">Write what you think.</p>
<p style="color:LightCoral;text-align:center;font-size: 150%;font-family: "Times New Roman", Times, serif;"">Write to decorate your thoughts with words</p>

<form action="" method="post">
<p align="center">
Full Name:<input type="text" name="Full_name"size="25"maxlength="30"><br><br>
User Name:<input type="text" name="User_Name"size="25"maxlength="30"><br><br>
Password:<input type="password" name="password"><br><br>
Email id:<input type="text" name="e-mail"size="30"><br><br>
DOB:<input type="date" name="DOB"><br><br>

Phone number:<input type="text" name="mobileno"size="30"><br><br>
<input type="submit" value="Submit">
<input type="reset" value="Clear All">
</p>
</form>
</body>
</html>

Open in new window

1
Julian HansenCommented:
Please submit the output to the following. Place this at the top of your script
echo "<pre>" . print_r($_POST, true) . "</pre>";

Open in new window

We need to see what is in the DOB post variable.
0
ste5anSenior DeveloperCommented:
Just a comment: Your HTML contains errors, also does you inlined CSS...

E.g.
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Blogger's Arena</title>
    <link href="generic.css" rel="stylesheet" type="text/css" />
    <link href="themes/1/js-image-slider.css" rel="stylesheet" type="text/css" />
    <script src="themes/1/js-image-slider.js" type="text/javascript"></script>
    <style>
        body {
            background: url(images/Blurred-Background-Sunset-3c-Free.jpg);
        }

        h1 {
            background-color: green;
            text-align: center;
            color: red;
        }

        #htmlcaption {
            display: none;
        }

        #p1 {
            color: LightCoral;
            text-align: center;
            font-size: 150%;
            font-family: "Times New Roman", Times, serif;
        }

        #p2 {
            color: LightCoral;
            text-align: center;
            font-size: 150%;
            font-family: "Times New Roman", Times, serif;
        }

        #pform {
            text-align: center;
            vertical-align: middle;
        }
    </style>
</head>

<body>
    <h1>Welcome to Blogger's Arena</h1>
    <div id="sliderFrame">
        <div id="slider">
            <img alt="(none)" src="images/blogging_image.jpg" />
            <img alt="(none)" src="images/blog-793047_960_720.jpg" />
            <img alt="(none)" src="images/download.jpg" />
            <img alt="(none)" src="images/to-blog.jpg" />
            <img alt="(none)" src="images/i-think.jpg" />
        </div>
        <div id="htmlcaption"> </div>
    </div>
    <div class="div2"> </div>
    <p id="p1">Write what you think.</p>
    <p id="p2">Write to decorate your thoughts with words</p>
    <form action="submit" method="post">
        <p id="pform">
            Full Name:
            <input type="text" name="Full_name" size="25" maxlength="30">
            <br>
            <br> User Name:
            <input type="text" name="User_Name" size="25" maxlength="30">
            <br>
            <br> Password:
            <input type="password" name="password">
            <br>
            <br> Email id:
            <input type="text" name="e-mail" size="30">
            <br>
            <br> DOB:
            <input type="date" name="DOB">
            <br>
            <br> Phone number:
            <input type="text" name="mobileno" size="30">
            <br>
            <br>
            <input type="submit" value="Submit">
            <input type="reset" value="Clear All">
        </p>
    </form>
</body>

</html>

Open in new window

0
Julian HansenCommented:
@Chris,

I thought the same thing re the format - however if you look at the output from his opening post the Query is coming through as

Error: INSERT INTO signin (F_name,U_name,password,email,DOB,phn)VALUES ('kkkk','qqqqq','77777','mmmmmmmmm','/2017-03-24/','10000000')
Incorrect date value: '/2017-03-24/' for column 'DOB' at row 1 

Open in new window

The YYYY-MM-DD input format would explain the other errors but not where the leading / trailing '/' in the final query string are coming from. ['/2017-03-24/']
1
Chris StanyonWebDevCommented:
On top of what Julian has said (dump your POST), you need to change lines 18-20 to the following:

$rawDoB = new DateTime($_POST['DOB']);
$DOB = $rawDoB->format("y-m-d"); // this will format your date to yyyy-mm-dd. Change according to your needs.

Open in new window

0
Chris StanyonWebDevCommented:
@Julian - good point. Along with the result and the undefined index, it's almost as if the DOB array is being concatenated with the slash - NULL/DOB[0]/NULL !!

Odd !
0
Julian HansenCommented:
I tried to replicate with his code and sending different DOB strings to it - couldn't get the results. That is why I think there is more to this than we are seeing.
0
Souvik MisrastudentAuthor Commented:
$date = $_POST['DOB'];
      $explode = explode("/", $date);
      $month  = $explode[0];
      $day = $explode[1];
      $year = $explode[2];
      $all = $month."-".$year."-".$day;
 that's the way I fixed it
1
Julian HansenCommented:
That makes no sense, breaking it up like that does not change anything - it is functionally the same as what you had to begin with.
I would still go with either my recommendation where
$date = isset($_POST['DOB']) ? $_POST['DOB'] : false;
if ($date) {
  $dob = date('Y-m-d', strtotime($date);
  ...
}

Open in new window

Or Chris'
$rawDoB = new DateTime($_POST['DOB']);
$DOB = $rawDoB->format("y-m-d"); // this will format your date to yyyy-mm-dd. Change according to your needs.

Open in new window


There are functions for doing what you want to do - you don't need to go re-inventing the wheel to do what is already available.
0
Chris StanyonWebDevCommented:
Well that doesn't really make sense, but glad you got it sorted !
0
Julian HansenCommented:
I don't understand the accepted solution.
The advice given in that solution is just plain wrong - it is stating that the inclusion of the array variables in the string is incorrect and concatenation should be used - but this is misleading - as the original string has nothing wrong with it.
0
mohan singhWeb developerCommented:
Hi @ Julian Hansen

He want to insert date in other format
am just suggest him

Is there any problem or mistake in my solution
so please tell me

and I think it is not a bad solution
Thank You
0
ste5anSenior DeveloperCommented:
btw, storing passwords is eval (Plain Text Offenders). Or at least a huge security issues. Store a salted (per user) hash instead. See Safe Password Hashing.
0
Julian HansenCommented:
Is there any problem or mistake in my solution
You posted this
<?php
 $DOB=$_POST['DOB'];
      $DOB = explode("/",$DOB);
      $DOB = "$DOB[2]-$DOB[0]-$DOB[1]";
This is wrong method
?>
Stating that what is being done here is wrong. This is incorrect - there is nothing wrong with the above and is definitely not the cause of the errors specified in the original post.
You recommended
<?php
  $DOB=$_POST['DOB'];
      $DOB = explode("/",$DOB);
      $DOB = $DOB[2]."-".$DOB[0]."-".$DOB[1];
This is correct way to change your / to -
?>
Stating this is the correct way - which is also misleading (as I pointed out in my post)
There is nothing wrong with embedding array variables (or any other variable) in a string - and to say that concatenation is the right way and variable embedding is the wrong way is not correct.

We still don't know what the problem was here - we are guessing it was bad input but without more information from the author we cannot say.

The fact that splitting up the exploded items "fixed" the problem - simply does not make sense - that does not explain the original errors.
0
Chris StanyonWebDevCommented:
I'm with Julian on this - the accepted solution is not the solution to the problem. The problem was not caused by the string builder:

$DOB = "$DOB[2]-$DOB[0]-$DOB[1]";

is functionally identical to this:

$DOB = $DOB[2]."-".$DOB[0]."-".$DOB[1];

so switching one out for the other does absolutely nothing for the functionality of the code.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
HTML

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.