Sending date and time form fields to MySQL with PHP - php

I've searched through the posts for an answer and the closest answer came from the topic "trying-to-post-date-via-php-with-mysql-need-help"
I've got a form with 2 input fields and .The user selects the date from an html5 popup calendar picker, types in the time, and submits the form to a mysql db. I'm having trouble getting the date and time fields to validate/upload to the db.
In my MySQL db I have a table called appointments with a column called curdate that has a type of DATE; another column is called curtime with a type of TIME.
My PHP file has the PHP validation and SQL actions at the top of the file and the sticky html form at the bottom. The form uses to send the form
Here is the code:
$td = date( 'Y-m-d H:i:s', $phpdate );
$phpdate = strtotime( $td );
if(isset($_POST['submitted'])) {
require_once('mysqli_connect.php');
$errors=array();
if(empty($_POST['curdate'])) {
$errors[]='Your date did not match';
} else {
$td=mysqli_real_escape_string($dbc,trim($_POST['curdate']));
}
if(empty($_POST['curtime'])) {
$errors[]='Your time is empty';
} else {
$tt=$_POST['curtime'];
}
if(empty($errors)) {
$q="INSERT INTO users (first_name,last_name,email,curdate,curtime,physician,reason) VALUES ('$fn','$ln','$e','$td','$tt','$phys','$reason')";
$r=#mysqli_query($dbc,$q);
if($r) {
echo '<h1>Thanks</h1>
<p>You are now registered</p><p><br/></p>';
} else {
echo '<h1>System Error</h1>
<p class="error">You could not be registered</p>';
echo '<p>'.mysqli_error($dbc).'<br/><br/>Query:'.$q.'</p>';
}
mysqli_close();
include('includes/footer.html');
exit();
} else {
echo '<h1>Error</h1>
<p class="error">The following errors occurred:<br/>';
foreach ($errors as $msg) {
echo "-$msg<br/>\n";
}
echo '</p><p> Please try again</p><p><br/></p>';
}
mysqli_close($dbc);
}

Mysql Or Mysqli Supports date format as 'yyyy-mm-dd' so u need to convert date and time in proper format before inserting in DB
If you want to insert current date and time when the user submits the form then Use following Query
INSERT INTO users (first_name,last_name,email,curdate,curtime,physician,reason)
VALUES ('$fn','$ln','$e',CURDATE(),CURTIME(),'$phys','$reason')
But if you want to insert date from form field then do following
$td=$_POST['curdate'];
$tt=$_POST['curtime'];
$td=date('Y-m-d',strtotime($td)); //Converts date to 'yyyy-mm-dd' acceptable to mysql
$tt=date('H:i:s',strtotime($tt)); //converts time to HH:mm:ss
//Now apply Your Query as
INSERT INTO users (first_name,last_name,email,curdate,curtime,physician,reason)
VALUES ('$fn','$ln','$e','$td','$tt','$phys','$reason')

You might have a problem, if you in mysql made that row in table dateandtime type, if that's the case you won't be able to store it like that. If you want it to be like that just use text or varchar ....
DATE - Stores a date value in the form YYYY-MM-DD. For example 2008-10-23.
DATETIME - Stores a date and time value of the form YYYY-MM-DD HH:MM:SS. For example 2008-10-23 10:37:22. The supported range of dates and times is 1000-01-01 00:00:00 all the way through to 9999-12-31 23:59:59
TIMESTAMP - Similar to DATETIME with some differences depending on the version of MySQL and the mode in which the server is running.

Related

Enter the date when the checkbox is selected

I'm trying to make it so that when the checkbox is selected it puts today's date in the database, I tried using timestamp but it puts it in all the spaces in the column, I'm a beginner in php
The code I made was this:
<?php
if (isset($_POST['Abate'])){
$Abate="Sim";
$data=time();
$DiaAbate= date("Y/m/d", $data);
}
else{
$Abate="Nao";
$DiaAbate="";
}
?>
You have not included your table structure (CREATE TABLE statement) so I have assumed you have a DATE column for storing $DiaAbate. I have also assumed that the submitted date is in 22/11/2022 format. If you are using a different format for the POSTed date value, you will need to change the format string passed into DateTime::createFromFormat().
Your current code is vulnerable to SQL Injection as you are combining your static strings with user input without any validation. The simple example below uses a prepared statement for the insert query -
if (isset($_POST['Abate'])){
$Abate = 'Sim';
// create a date from the posted date string adn format it
// see https://www.php.net/manual/en/datetime.createfromformat.php
$DiaAbate = DateTime::createFromFormat('d/m/Y', $_POST['DiaAbate'])->format('Y-m-d');
} else {
$Abate = 'Nao';
$DiaAbate = null;
}
$query = 'INSERT INTO pc (Abate, DiaAbate) VALUES (?, ?)';
$query_run = mysqli_execute_query($con, $query, [$Abate, $DiaAbate]);
if ($query_run) {
$_SESSION['status'] = 'Inserted Succesfully';
header('Location: indexx.php');
} else {
$_SESSION['status'] = 'Not Inserted';
header('Location: indexx.php');
}

Get date and time retrieved from database into a datetime input

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');

Date value is not inserting or updating in MySQL Database Prestashop

When I update my date field in MySql database Prestashop It's not inserting in the table where column type is "Date".
And when I change the column type to "varchar" , It's calculating the date means If date comes in this format 2016-4-2 then value will be stored "2010". And when I place date manually in the query then it works. Please help me out.
if (Tools::getValue('id_abono')) {
print_r($_POST['datetex']);
$dtt= $_POST['datetex'];
$dtr= date("Y-m-d H:i:s", $dtt);
Db::getInstance()->execute('Update '._DB_PREFIX_.'lgabonos set date='.$dtr.'
WHERE id_abonos = '.pSQL(Tools::getValue('id_abono')).'');
$output .= #Module::displayConfirmation($this->l('The credit note has been successfully updated'));
}
Try this query :
Db::getInstance()->execute('Update '._DB_PREFIX_.'lgabonos set date="'.$dtr.'"
WHERE id_abonos = '.pSQL(Tools::getValue('id_abono')).'');
I think it will solve your problem

Inserting a date to database

I am having a form with two textboxes where i am displaying the month calender like in any other online forms to select the date. The user selects the date. I want the user to select a date which is equal to or after the system date like tomorrow. I am comparing the dates and then trying to insert it into the database with two columns opening_date and closing dates. I don't even want the textbox to be left empty. I have the below code but isn't working out.
<?php
mysql_select_db("trials");
if(isset($_POST['next']))
{
$odate=date("Y-m-d");//system date
echo $odate;
if(($_POST['date1']>$odate)||($_POST['date1']==$odate)&&($_POST['date1']!=""))
{
$s=mysql_query("insert into registration_date (opening_date, closing_date) values('$_POST[date1]','$_POST[date2]')");
echo $s;
if(mysql_query($s))
{
echo "successful";
}
else echo "error".mysql_error();
}
else
echo "Enter A Valid Date";
}
?>
You're also using mysql_query twice once on the set of $s and then your doing mysql_query($s) later on which is in effect doing mysql_query(mysql_query("sql"))
$s=mysql_query("insert into registration_date (opening_date, closing_date) values('$_POST[date1]','$_POST[date2]')");
echo $s;
if(mysql_query($s))
Replace
if(($_POST['date1']>$odate)||($_POST['date1]==$odate)&&($_POST['date1']!=""))
with this
if(($_POST['date1']>$odate)||($_POST['date1']==$odate)&&($_POST['date1']!=""))
You have missed one quote for date1 and also try like
$open_date = $_POST['date1'];
$close_date = $_POST['date2'];
$s=mysql_query("INSERT INTO registration_date (opening_date, closing_date)
VALUES ('$open_date','$close_date')");
And try to avoid using mysql_* functions due to they are depricated.Instead use mysqli_* functions or PDO statements
get system date with function time() like this: $odate=time(); and trasform $_POST[date] in a number like this: strtotime($_post[date]). After this you can do this: $_POST[date]>$odate. in this way you will have two numbers to compare.

Time restrictions in php/mysql

I have different events wherein users can sign-up. These events have their own date and time schedules. How do I add a sort of a time restriction wherein it will automatically restrict the users from signing up?
For Example, I have an event scheduled on March 10, 2012. Users will only be allowed to sign-up for the event up to March 9, 2012.
My table for the events contains the following fields:
eventID/eventName/eventTime/eventDate/eventCapacity/eventDescription
Thanks for your help!
Get event using eventTime/eventDate parameter and check today's date is smaller or not using datediff function.if date is bigger then reuse to accept.
Retrieve the event date and the current date and calculate the difference using PHP date object
mysql_connect("localhost", "root", "");
mysql_select_db("myDb")
$query="SELECT * FROM events WHERE eventName='$eventName' ";
$result=mysql_query($query);
$row=mysql_fetch_array($result);
$currentTime= new DateTime("now UTC");
$eventTime=new DateTime($row['thisEventDate']);
$interval=$eventTime->diff($currentTime);
$days=$interval->format('%d');
if($days<=1) {
print "sorry too late, we're sold out";
}
else {
//allow for registration fields.
}
By comparing the current date and desired date or taking the difference or current date and desired date, and accordingly displaying the HTML form into the PHP if loop
Sample
if($days<=1) {
echo "where were you wen i asked you to do so!!! ";
}
else {
<form>
field1
field2
...
</form>
}
here, $days is difference of dates

Categories