How to insert norman date in mysql using php? - php

I'm totally new to php and mysql & need some help with this.
I want to insert a date into a mysql table, formatted as dd/mm/yyyy.
I have 4 columns in my table: id, name, age & birthday.
MY HTML-CODE
<form action="php_creat_cliente.php" method="post">
Name : <input name="reference" type="text" /><br />
Age : <input name="focode" type="text" /><br />
Birthday : <input name="date" type="text" /><br />
</form>
MY PHP-CODE
<?php
include('config.php');
$name=$_POST['name'];
$age=$_POST['age'];
$birthday=$_POST['birthday'];
$save=mysql_query("INSERT INTO loan (name, age, birthday) VALUES ('$name', '$age', '$birthday')");
header("location: index.html");
exit();
?>
Currently, the date is inserted in the mm/dd/yyyy format, but I need it in the dd/mm/yyyy format.

You have several ways, but the best if you are inserted as date or timestamp.
The first way is, if you store it in a varchar field, but in this case you can not use the mysql date functions.
Insert in regular way: YYYY-MM-DD
And, when you need it, you can use the mysql date functions to format it, or you can format it with php code also.
If you are assuming, your $_POST['birthday']; comes in mm-dd-yyyy format, then you should do something like this
//This varaible will come from the form, this is just a test now!
$_POST["birthday"] = 'mm-dd-yyyy';
$month = substr($_POST["birthday"], 0, 2);
$day = substr($_POST["birthday"], 3, 2);
$year = substr($_POST["birthday"], 6);
$birthday = $year . "-" . $month . "-" . $day;
$save = mysql_query("INSERT INTO loan (`name`, `age`, `birthday`) VALUES ('".$name."','".$age."','".$birthday."')");

MySQL accepts a string in the format of 'yyyy-mm-dd' or 'yyyymmdd' for dates. So you can enter it in the text field in whichever format you want as long as you make sure you reformat it (in your code) to a valid format (like the ones I mentioned) before passing it to the database.
Or you can specify the format yourself like so:
$save=mysql_query("INSERT INTO loan (name, age, birthday)
VALUES ('$name', '$age', STR_TO_DATE('$birthday', '%d-%m-%Y'))");
The jQuery UI Datepicker widget is popular for dates in forms.
As others have mentioned the current way you're doing this (at least the way shown here) is prone to SQL injection, XSS, CSRF, and everything in between. I'd advise you to learn about these attacks if you are to become a web developer.
EDIT:
What jQuery UI Datepicker helps with is picking a date and placing it in the text field in a valid date format. You can specify the format in which you want the widget to show your date like this:
$( "#datepicker" ).datepicker( "option", "dateFormat", "dd-mm-yy" );
And then you can make sure MySQL accepts the date format you're submitting in your insert command by specifying it like I showed above:
STR_TO_DATE('$birthday', '%d-%m-%Y')

Related

What's the proper way to get a datetime-local value from the input and insert it into a database?

I have a form with a datetime-local input and I'm looking for how to extract the value of the date and time that the user has inputted into this datetime-local and pass its value into a column named listDates in my database table called date_table;
My database connection works fine and everything. And I have more of these similar functions that adds simple strings form textboxes and they all work fine. It's just the datetime-local that's not registering (or rather only registers it as 0000-00-00 00:00:00 (the initial datetime value of January 1, 1970).
How may I properly get the value of datetime-local and pass it into my database? Thank you for any help you can offer, I'm only stuck with this particular part with coding PHP and MySQLi.
My Form
<form>
<input name="theDate" type="datetime-local" required>
<a href="dateCRUD.php?theDate=<?php $_GET['theDate'] ?>&action='addDate'"</a>
<!--I'm not sure if $_GET should be the proper way to get the datetime-local value-->
</form>
My dateCRUD php where I add, update, delete dates from a database table called date_table
$theDate = isset($_REQUEST['theDate']);
switch($_REQUEST['action']){
case 'addDate':
{
addDate($theDate);
break;
}
}
My php MySQLi function to addDate()
function addDate($theDate)
{
global $conn; //my connection to my database which works fine.
$query = 'INSERT INTO date_table SET listDates = ?';
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $theDate) //can datetime-local be a 'string'?
$stmt->execute();
}
EDIT
If it helps, I set my listDate type to 'datetime' in my date_table in my database. Should I change it to 'string' type instead?
Problem in your form where you are try to send datetime-local input to server and store to database. Type datetime of date_table in database is fine. Datetime store datetime-local value. In your form <a href="dateCRUD.php?theDate=<?php $_GET['theDate'] ?>&action='addDate'"</a>, <?php $_GET['theDate'] ?> does't send date time local value to server. You should send form value using a button in form. Like as
<form method="post" action="dateCRUD.php&action=addDate">
<input name="theDate" type="datetime-local" required>
<input type="submit" name="addDate">
</form>
Update your php code as
if(isset($_POST['addDate'])){
$theDate = isset($_POST['theDate']);
switch($_REQUEST['action']){
case 'addDate':
{
addDate($theDate);
break;
}
}
}
Use the same MySQL function for store date in database.

Use datetime data from SQL query to populate "input type=time" field

I'm trying to get an SQL query with PHP to populate various fields in a form so they can be edited by a site administrator. Those two fields are date and time.
I'm using the two input types 'date' and 'time'. The date field is populating perfectly. The time field is coming up blank. The data for both is coming from the same SQL query. I'd like them both to display within the intended format for each field. (I'm using Chrome for this as I know the field types aren't supported by all browsers).
//Queries
$pull_game = "select datetime, city, opponents.opponent_id, game_type, tourn_name, time, home_score, vis_score, day_of_week, month, day, year, parks.park_id, park, win, loss, tie, result from games, opponents, parks, tournaments where opponents.opponent_id = games.opponent_id and parks.park_id = games.park_id and tournaments.tourn_id = games.tourn_id and game_id= ".$_POST['game_id'] . ";";
$game_stats = mysqli_query($con,$pull_game) or die("ERROR: $pull_game. ".mysqli_error());
$game = mysqli_fetch_array($game_stats);
//Display data
<input type='date' name='date' value=<?= $game['datetime']?>>
<input type='time' name='time' value=<?= $game['datetime']?>>
I've tried eliminating the date field to see if the time field would work, but it still came up blank. I've had no luck researching this - most of the content I find is for updating the DB with datetime data. I'm looking for the opposite (sort of).
Any help would be appreciated.
//Queries
$pull_game = "select date(datetime) as d, time(datetime) as t, city, ..."
//Display data
<input type='date' name='date' value=<?= $game['d']?>>
<input type='time' name='time' value=<?= $game['t']?>>
should do the trick. Valid date and time formats for HTML5 inputs are described in https://www.w3.org/TR/html5/infrastructure.html#dates-and-times - essentially it's YYYY-MM-DD for "date", and HH:MM:SS for "time" inputs. Conveniently, this is exactly the output MySQLs date() and time() functions yield (cp. http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html).
you could use a substr function to escape the chracters from the date and add only the time or you can also try using the strtotime function too, to convert the data type you are getting from the query and put it into the fields you need
$date2=date('Y-m-d', strtotime($date));
check the strtotime function here
Also I don't think there is a input type="time" so, check the existsent input types

How do I take values from 3 fields (Month, Day, Year) and have all three of these fields inserted as a single field (MySQL)?

I've created an HTML form and its corresponding insert.php code. The question I have is this:
1) Does PHP read the ID or NAME field (HTML) when the user presses submit on an HTML form?
2) How do I use PHP to combine fields so that it is inserted into a MySQL Database in a single column/field? (I'm trying to be more specific; last few Questions of mine were flagged on Stack, so I'm -trying- to adhere to the community standard)
<label class="description" for="element_23">Date of Birth </label>
<span>
<input id="element_23_1" name="applicants.DOB_month" class="element text" size="2" maxlength="2" value="" type="text"> /
<label for="element_23_1">MM</label>
</span>
<span>
<input id="element_23_2" name="applicants.DOB_day" class="element text" size="2" maxlength="2" value="" type="text"> /
<label for="element_23_2">DD</label>
</span>
<span>
<input id="element_23_3" name="applicants.DOB_year" class="element text" size="4" maxlength="4" value="" type="text">
<label for="element_23_3">YYYY</label>
</span>
--MySQL--
$sql = "INSERT INTO applicants (fname, lname, address, city, state, zip, country, phone, school, DOB, age, amount_requested) VALUES ('$applicants_fname', '$applicants_lname', '$applicants_address','$applicants_city','$applicants_state','$applicants_zip','$applicants_country','$applicants_phone','$applicants_school','$DOB','$age', '$applicants_amount_requested')";
To create 1 field in DB from 3 fields with data from your form you can get all this 3 fields (from $_POST оr $_GET array (this param must be in <form>s action attribute)):
$value = $_POST['field1_name'].'/'.$_POST['field2_name'].' /'.$_POST['field3_name'];
and then insert it into DB.
it depends of your column type but if this is a string,
you can use MySQL CONCAT
INSERT INTO `table`(`field`) VALUES (CONCAT('val1', '/', 'val2', '/', 'val3'));
on form submit, the request string is created from the name fields, not the id. Thus the request is name1=value1&name2=value2 ....
You have to create the valid value to insert in the right field. You can use php and concatenate values $values = $_POST['name1'] . 'delimiter' . $_POST['name2'] or you can use the SQL CONCAT function.
Assign a new variable and concatenate the ones you want to be entered in the db, then use that variable as the final product.
I.e.: and assuming a POST form method, since you did not specify that in your question.
$year = $_POST['applicants.DOB_year'];
$month = $_POST['applicants.DOB_month'];
$day = $_POST['applicants.DOB_day'];
$DOB = $year . "-" . $month . "-" . $day;
$sql = "INSERT INTO applicants
(fname, lname, address, city, state, zip, country, phone, school, DOB, age, amount_requested)
VALUES ('$applicants_fname', '$applicants_lname', '$applicants_address','$applicants_city',
'$applicants_state','$applicants_zip','$applicants_country','$applicants_phone','$applicants_school',
'$DOB','$age', '$applicants_amount_requested')";
You'll also want to set your column as a DATE type since MySQL stores that as YYYY-MM-DD.
https://dev.mysql.com/doc/refman/5.1/en/datetime.html
The reason being that it will be easier to query later. You will have a harder time if your column is set to VARCHAR and would have to result in using more functions/resources than what is required.
Use MySQL's built-in DATE functions.
The above will render something like 1995-12-22
From the manual:
The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.
You should also use a prepared statement, since your code may be prone to an SQL injection. It is unknown if you are escaping your data.
https://en.wikipedia.org/wiki/Prepared_statement
"1) Does PHP read the ID or NAME field (HTML) when the user presses submit on an HTML form?"
If you're using pure PHP, then it relies on the "name" attribute.
Consult http://php.net/manual/en/tutorial.forms.php
JS/Ajax however, does support the ID attribute though.
Consult http://webdesign.tutsplus.com/tutorials/building-a-bootstrap-contact-form-using-php-and-ajax--cms-23068

Insert jQuery Date in MySQL

I have been trying to follow the example shown from this link below:
PHP mysql insert date format
This is my code sample below:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
/** Variables */
$pdate = isset($_POST['pdate']) ? $_POST['pdate'] : '';
$org = mysqli_escape_string($dbcon, trim($_POST['org']));
$city = mysqli_escape_string($dbcon, trim($_POST['city']));
$state = isset($_POST['state']) ? $_POST['state'] : '';
$rio = mysqli_escape_string($dbcon, trim($_POST['rio']));
/** Query */
$q = "INSERT INTO `survey` (id, pdate, org, city, state, rio, date_created)
VALUES (NULL, STR_TO_DATE('$pdate', '%M %d, %Y'), '$org', '$city', '$state', '$rio', NOW())";
?>
/** Changing Datepicker Value **/
jQuery(document).ready(function($) {
/** Datepicker for the Form */
$('.selector').datepicker('option', 'dateFormat', 'yy-mm-dd');
});
$pdate = "2015-09-28"; Displays like that according to the <?php echo format ?>
There are two queries that you are using, should I use the STR_TO_TIME() or FROM UNIXTIME()
When I try and follow the 3rd step:
$dt = DateTime::createFromFormat('m/d/Y', $_POST['pdate']);
$pdate = $dt->format('Y-m-d');
After submitting the form, I get undefined variable index.
What is it that I am now missing?
You didn't post the most important information - actual error message - so I can only guess, what's wrong. These are my guesses:
If undefined index is pdate, than you don't have such form control. That could be the raeson, why you have "0000-00-00" as a date in your DB
You have configured Datepicker to output date in a format yy-mm-dd, but you're parsing it as %M %d, %Y in MySQL function STR_TO_DATE or m/d/Y in PHP DateTime's method createFromFormat. That doesn't make a sense.
Since yyyy-mm-dd is MySQL's native format to express a date, you don't need any conversion at all. Just save into a DB what you get from Datepicker.
So I would start with this:
Check what you're getting from your form in PHP, e.g. print what's in $_POST array: var_dump($_POST)
Check if there is a key pdate and contains date in format yyyy-mm-dd
Save it to DB. You're done.
The easiest way to Insert Date Format is to do the following using jQuery Date Format See - http://api.jqueryui.com/datepicker/#option-dateFormat
`jQuery`
$( ".selector" ).datepicker({
dateFormat: "yy-mm-dd"
});

PHP Date not inserting to mysql

Hi I don't know what's the problem. The date field is not inserting to mysql.The format should be in YYYY-MM-DD like in mysql. Maybe that's the problem? The date in the input type is mm-dd-yyyy.
Query:
if(isset($_POST['subButton']))
{
mysql_query("INSERT INTO order_queue (Date, Tracking, Name, Address,
ContactNo, dateneed, Payment, Claiming, qtyBlackWhite,
totalBlackWhite, qtyChocnut, totalChocnut, qtyHotMama, totalHotMama,
qtyMocha, totalMocha, qtyUbeKeso, totalUbeKeso, GrandTotal)
VALUES (NOW(), '".$_POST['Tracking']."', '".$_POST['Name']."',
'".$_POST['Address']."', '".$_POST['ContactNo']."',
'".$_POST['dateneed']."', '".$_POST['Payment']."',
'".$_POST['Claiming']."', '".$_POST['qtyBlackWhite']."',
'".$_POST['totalBlackWhite']."', '".$_POST['qtyChocnut']."',
'".$_POST['totalChocnut']."', '".$_POST['qtyHotMama']."',
'".$_POST['totalHotMama']."', '".$_POST['qtyMocha']."',
'".$_POST['totalMocha']."', '".$_POST['qtyUbeKeso']."',
'".$_POST['totalUbeKeso']."', '".$_POST['GrandTotal']."')");
}
html
<input type="date" name="dateneed" id="dateneed" />
The date input type is mm/dd/yyyy.
In mysql the dateneed field is in DATE datatype and NN. What's wrong? In the query the Date is the auto inserting of date when the form is submitted. The problem is the dateneed is kinda preventing the form from insert everything. T__T
There are more problems with it.
As other suggested, first of all, don't use PHP mysql extension, use mysqli or PDO.
Second, always check for EVERY user input data, and format them according to your query.
Use parameters in your SQL or escape the values you insert.
But to answer your question, use this:
$d = explode('/',$_POST['dateneed']);
$date = $d[2].'-'.$d[0].'-'.$d[1];
But you should check the date to be valid.
You Just have to pass fieldname is dateneed instead of Date
if(isset($_POST['subButton']))
{
mysql_query("INSERT INTO order_queue (dateneed, Tracking, Name, Address,
ContactNo, dateneed, Payment, Claiming, qtyBlackWhite,
totalBlackWhite, qtyChocnut, totalChocnut, qtyHotMama, totalHotMama,
qtyMocha, totalMocha, qtyUbeKeso, totalUbeKeso, GrandTotal)
VALUES (NOW(), '".$_POST['Tracking']."', '".$_POST['Name']."',
'".$_POST['Address']."', '".$_POST['ContactNo']."',
'".$_POST['dateneed']."', '".$_POST['Payment']."',
'".$_POST['Claiming']."', '".$_POST['qtyBlackWhite']."',
'".$_POST['totalBlackWhite']."', '".$_POST['qtyChocnut']."',
'".$_POST['totalChocnut']."', '".$_POST['qtyHotMama']."',
'".$_POST['totalHotMama']."', '".$_POST['qtyMocha']."',
'".$_POST['totalMocha']."', '".$_POST['qtyUbeKeso']."',
'".$_POST['totalUbeKeso']."', '".$_POST['GrandTotal']."')");
}
YOu can manipulate the dateneed value into require format then we can store it to database.
if(isset($_POST['subButton']))
{
$dateneedExplode = explode('-',$_POST['dateneed']);
$dateneedValue = $dateneedExplode[2].'-'.$dateneedExplode[0].'- '.$dateneedExplode[1];
mysql_query("INSERT INTO order_queue (Date, Tracking, Name, Address,
ContactNo, dateneed, Payment, Claiming, qtyBlackWhite,
totalBlackWhite, qtyChocnut, totalChocnut, qtyHotMama, totalHotMama,
qtyMocha, totalMocha, qtyUbeKeso, totalUbeKeso, GrandTotal)
VALUES (NOW(), '".$_POST['Tracking']."', '".$_POST['Name']."',
'".$_POST['Address']."', '".$_POST['ContactNo']."',
'".$dateneedValue."', '".$_POST['Payment']."',
'".$_POST['Claiming']."', '".$_POST['qtyBlackWhite']."',
'".$_POST['totalBlackWhite']."', '".$_POST['qtyChocnut']."',
'".$_POST['totalChocnut']."', '".$_POST['qtyHotMama']."',
'".$_POST['totalHotMama']."', '".$_POST['qtyMocha']."',
'".$_POST['totalMocha']."', '".$_POST['qtyUbeKeso']."',
'".$_POST['totalUbeKeso']."', '".$_POST['GrandTotal']."')");
}

Categories