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"
});
Related
i would like to help with my code how to edit HTML input date into MySQL TIMESTEMP format cause my SQL code is invalid and data are not added to my database, Thanks for help
also i asking to check this code on bottom cause 2nd SQL deppends on 1st SQL, thanks
if (isset($_POST['pridaj_anime_submit'])) {
$sql_vloz_anime = "INSERT INTO anime (a_name, a_year, a_translated_min, a_translated_max, a_rate_min, a_rate_max, a_edit, a_condition)
VALUES ('$_POST[nazov]', '$_POST[rok]', '0', '$_POST[pocet]', '8', '10', '$_POST[preklad]', '$_POST[stav]')";
mysqli_query($connect_to_db , $sql_vloz_anime);
$sql_ziskaj_a_id_pridaneho_anime = "SELECT * FROM anime WHERE a_name = '$_POST[nazov]'";
$run_sql_ziskaj_a_id_pridaneho_anime = mysqli_query($sql_ziskaj_a_id_pridaneho_anime);
$a_id_ziskane = "";
while ($db_data = mysqli_fetch_assoc($run_sql_ziskaj_a_id_pridaneho_anime)) {
$a_id_ziskane = $db_data['a_id'];
}
$sql_vloz_anime_info = "INSERT INTO anime_info (a_id, a_img, a_start, a_stop, a_time_ep, a_akihabara)
VALUES ('$a_id_ziskane' , '$_POST[obrazok]', '$_POST[zaciatok]', '$_POST[koniec]', '$_POST[cas]', '$_POST[akihabara]')";
mysqli_query($connect_to_db , $sql_vloz_anime_info);
}
$input_date=$_POST['date'];
$date=date("Y-m-d H:i:s",strtotime($input_date));
This will convert input date into MySQL Timestamp compliant format.
Please DO NOT put POST values directly in your queries. Your website or web application will be hacked in no time through SQL Injections.
MySql datetime considered yyyy-mm-dd h:i:s format.
Your input date is like dd-mm-yyyy h:i:s and so on.
Then use convert date to yyyy-mm-dd h:i:s. Read strtotime manual.
For e.g.
$inputDate = '06-06-2017 05:21:34';
$mysqlDate = date("Y-m-d H:i:s",strtotime($inputDate));
// MySql Query.
INSERT INTO table_name SET `your_field`='$mysqlDate'
I'm trying to retrieve a Datetime value from my database and place it in an html input with a date type but it doesn't show anything.
$resQuery = mysql_query("SELECT * FROM reserveringen WHERE id = $ID");
while ($resInfo = mysql_fetch_array($resQuery))
{
$dateTime = $resInfo[3];
}
<?php echo "<input name='dateTime' type='datetime-local' value='$dateTime'"?>
Also when I F12 I get this error: The specified value "2525-0505-16161616 0606:0505" does not conform to the required format. The format is "yyyy-MM-ddThh:mm" followed by optional ":ss" or ":ss.SSS".
This fixed it for me guys!
I changed my query to:
SELECT *, DATE_FORMAT(Datum, '%Y-%m-%dT%H:%i') AS Datum_conv FROM reserveringen WHERE id = $ID
The problem is that when you was writing data into database you used wrong date format. Look carefully at datetime value:
2525-0505-16161616 0606:0505
It must be
25-05-16 06:05
What you did when saving data is using these date format:
date('dd-mm-yyyy HH:ii')
instead of this
date('d-m-Y H:i');
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')
I have a page that shows user activity, I have built a form where the user can filter this by date.
Here is the form
<form action='filter_activity.php' method='get'>
From: <input type='text' name='from' value='dd/mm/yyyy'>
To: <input type='text' name='to' value='dd/mm/yyyy'>
<input type='submit' value='Filter'>
Here is the filter_activity.php page:
$from=$_GET["from"];
$to=$_GET["to"];
$result=mysql_query("SELECT * FROM member WHERE personID=$user AND created between $from and $to ");
However this shows nothing, can anyone help?
Your posted dates are in invalid format for DB use. You need to convert them before use in DB.
$from = DateTime::createFromFormat('d/m/Y', $_GET['from']);
$to = DateTime::createFromFormat('d/m/Y', $_GET['to']);
$sql = "
SELECT *
FROM member
WHERE personID = $user AND created BETWEEN '%s' AND '%s'
";
$sql = sprintf($sql, $from->format('Y-m-d'), $to->format('Y-m-d'));
Plus, you should check if $_GET keys exists and after that, check if $from and $to are DateTime object, and not false.
you need to cast it to date like:
$result=mysql_query("SELECT * FROM member WHERE personID=$user AND created BETWEEN DATE('$from') AND DATE('$to')") or die(mysql_error());
from the site :
For best results when using BETWEEN with date or time values, use CAST() to explicitly
convert the values to the desired data type. Examples: If you compare a DATETIME to two
DATE values, convert the DATE values to DATETIME values.
If you use a string constant such as '2001-1-1' in a comparison to a DATE,
cast the string to a DATE.
Pass the correct date format to the DB:
$from = date('Y-m-d', strtotime(str_replace('/', '-', $_GET["from"])));
$to = date('Y-m-d', strtotime(str_replace('/', '-', $_GET["to"])));
$result = mysql_query("SELECT * FROM member WHERE personID=$user AND created BETWEEN '$from' AND '$to'");
Really think about changing the format in your form. I would use a date picker, either year/month/day dropdowns or javascript.
Also, read the other comments about quoting, SQL injection, etc. And get off of mysql_* functions.
I'm using JQuery datepicker to allow user select a day and book something.
then I save the date in database,
later on I get the dates out of database and disable those days in datapicker so next user can't select the booked days.
so far so good.
when a user select the day they want to book I need to disable the day after too.
I'm using php to save the chosen date in database together with some other information about user.
then i use ajax to load the dates thru php again and disable them.
how can i disable the they after? do I do it with php or javascript?
I have no idea how to get the day after selected date and how to save it? or should i save it or just add it later on when I get back the first date from ajax call and then loop thru the dates and get the day after with some function?
I would use PHP if you can by simply returning a list of dates to the beforeShowDay method of your DatePicker.
When you are adding a date from the database to the list, also use strtotime($Date, '1 day') to add the next day.
Edit:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT distinct Date, DATE_ADD(Date, INTERVAL 31 DAY) as Tomorrow from Table";
$result = $mysqli->query($query);
$Dates = array();
/* numeric array */
while(($row = $result->fetch_array(MYSQLI_NUM)) !== null)
{
//$Tomorrow = strtotime('1 day', $row['Date']);
$Tomorrow = $row['Tomorrow'];
if(!in_array($row['Date'], $Dates)) $Dates[] = $row['Date'];
if(!in_array($Tomorrow, $Dates)) $Dates[] = $Tomorrow;
}
/* free result set */
$result->free();
/* close connection */
$mysqli->close();
header('content-type: application/json');
die(json_encode(array('Dates' => $Dates)));
You can use PHPs strtotime() function:
strtotime("+1 day", $reservationDate)
You can call any javascript function onSelect of datepicker
for just an example
onSelect: function(dateText, inst){
//dateFormat: 'DD, MM d, yy'
var theDate = $(inst).datepicker.formatDate('DD, MM d, yy', $(inst).datepicker.('getDate'));
$("#temp_date_start").text(theDate);
}
If I would have to solve this problem. I would do this by sending one date to PHP (from JavaScript) and then use PHP to add both dates to the database. So I would use the PHP date functionality to get the next day (for example with http://www.php.net/manual/en/datetime.add.php). This because working with dates in JQuery isn't as easy as in PHP, but it's not because it isn't easy that it is impossible of course :-)
But if you want to use the functionality in real time. So for example if you don't have a page refresh between clicking on the selected date and disabling those dates. In that case I would suggest that your PHP background call returns the dates to disable (or the ids of the elements or something like that).
tl;dr: Send one date to PHP, use PHP date functions to get next day, save both dates in your database
$("#elementID").datepicker({
onSelect: function(selectedDate) {
var minDate = $(this).datepicker('getDate'); //get selectedDate
minDate.setDate(minDate.getDate()+1); //adds one day to minDate
//do whatever you do to disable the date using "minDate"
}
});