I have been searching for a while now, but I cannot put together enough information in order to resolve this problem.
I created an event calendar with a field that allows the user to enter a range for booking an event. I already have the start date configured for the date selected. When a user enters the end date, the information in the fields will be duplicated for each date in the range.
$requester = $_POST['txtrequester'];
$title = $_POST['txttitle'];
$detail = $_POST['txtdetail'];
$startTime = $_POST['txtstarttime'];
$endTime = $_POST['txtendtime'];
$endDate = $_POST['txtenddate']; //end date of range request
$eventdate = $month."/".$day."/".$year;
$today_dt = $year."-".$month."-".$day;
$startDate_dt = strtotime("$year."-".$month."-".$day");
$endDate_dt = strtotime($endDate);
$endDate_dt = $endDate_dt->modify('+1 day');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($today_dt, $interval, $endDate_dt);
Can someone help me figure this out? Thanks in advance
--Edit--
Code inserting event form data into mysql
$sqlinsert = "INSERT INTO conferenceevents (Requester,Title,Detail,eventDate,dateAdded,startTime,endTime,endRange) values ('$requester','$title','$detail','$eventdate',now(),'$startTime','$endTime','$endDate')";
$resultinsert = $connection->query($sqlinsert);
if($resultinsert){
echo "<h4>Event was Successfully Added</h4><br>";
}else{
echo "<h4>Event Failed to be Added</h4><br>" . $sqlinsert;
}
}
Event form html
<form name='eventform' method='POST' action="<?php $_SERVER['PHP_SELF']; ?>?month=<?php echo $month;?>&day=<?php echo $day;?>&year=<?php echo $year;?>&v=true&add=true">
<div class="form-group">
<label for="requester">Requester</label>
<select class="form-control" name='txtrequester'>
<option name='txtrequester'>Melissa</option>
<option name='txtrequester'>Greg</option>
<option name='txtrequester'>Matt</option>
<option name='txtrequester'>Michael</option>
<option name='txtrequester'>Ben</option>
<option name='txtrequester'>Pat</option>
<option name='txtrequester'>Maria</option>
</select>
</div>
<div class="form-group">
<label for="eventTitle">Event Title</label>
<input type="text" class="form-control" id="eventTitle" placeholder="Event Title" name='txttitle'>
</div>
<div class="form-group">
<label for="eventStartTime">Event Start Time</label>
<input type="time" class="form-control" id="eventStartTime" value="12:00" name='txtstarttime'>
</div>
<div class="form-group">
<label for="eventEndTime">Event End Time</label>
<input type="time" class="form-control" id="eventEndTime" value="13:00" name='txtendtime'>
</div>
<a href class="option"><h4>Click here to enter date range (optional)</h4></a>
<div class="form-group range" style="display: none;">
<label for="eventStartDate">Event Start Date</label>
<input type="text" class="form-control" id="disabledInput" name='txtstartdate' disabled value="<?php echo $month . "/" . $day . "/" . $year; ?>">
</div>
<div class="form-group range" style="display: none;">
<label for="eventEndDate">Event End Date</label>
<input type="date" value="<?php echo $year . "-" . $month . "-" . $day; ?>" class="form-control" id="eventEndDate" name='txtenddate'>
</div>
<div class="form-group">
<label for="eventDetail">Event Detail</label>
<input type="text" id="eventDetail" type="text" class="form-control" placeholder="Event Detail" name='txtdetail'>
</div>
<button type="submit" class="btn btn-default" name='btnadd'>Add Event</button>
</form>
It seems you are trying to insert a row in to your data base for each and every date in given date range... Please try it like this
$startTime = strtotime( '2015-01-11' );
$endTime = strtotime( '2015-01-20' );
// Loop between timestamps, 24 hours at a time
for ( $i = $startTime; $i <= $endTime; $i = $i + 86400 ) {
$given_date = date( 'Y-m-d', $i )."<br>";
// You can put your database insert query here
echo "Data for $given_date is inserted";
}
More efficient way of inserting multiple rows is as follows..
$startTime = strtotime( '2015-01-11' );
$endTime = strtotime( '2015-01-20' );
$sqlinsert = "INSERT INTO conferenceevents (Requester,Title,Detail,eventDate,dateAdded,startTime,endTime,endRange) values ";
// Loop between timestamps, 24 hours at a time
for ( $i = $startTime; $i <= $endTime; $i = $i + 86400 ) {
$eventdate =date('Y-m-d', $i );
// Constructing the insert query
$sqlinsert .= " ('$requester','$title','$detail','$eventdate',now(),'$startTime','$endTime','$endDate'),";
}
$bulk_insert_query = rtrim($sqlinsert, ","); // to remove last comma
$resultinsert = $connection->query($bulk_insert_query);
To get more understanding about bulk insert query Try to echo $bulk_insert_query and see how it was constructed and how you want to improve..
Related
Hi i am facing a problem while editing the plugin. the default time format of this plugin is 24 hours but i want to convert it into 12 hours with AM/PM as well.
Here is the code that i have
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group qc-input-container">
<select name="quickcab_form_departure_time_hour" id="quickcab_form_departure_time_hour" class="booking-input quickcab-select-input form-control" required>
<option disabled selected><?php echo esc_html__('Hour', 'quickcab'); ?></option>
<?php
for ( $i = 1; $i <= 12; $i++ ) {
?>
<option value="<?php echo sprintf('%02d', $i); ?>"><?php
echo sprintf('%02d', $i);
?></option>
<?php
}
?>
</select>
</div>
You can easily get the 12 hours time by using date() function. I'm giving an example for you.
// suppose your time is 19:24:15
$date = '19:24:15';
echo date('h:i:s a', strtotime($date));
The output will be
07:24:15 pm
You can get the output also by using DateTime
$date = new DateTime('19:24:15');
echo $date->format('h:i:s a') ;
h is used for 12 digit time
i stands for minutes
s seconds
a will return am or pm (use in uppercase for AM PM)
To keep it really simple you could just add another loop to 12 to get a full 24 hours, then a simple change to the sprinf() will get you the AM and PM, like this
sprintf('%02dAM', $i);
and in the second loop
sprintf('%02dPM', $i)
So your code
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group qc-input-container">
<select name="quickcab_form_departure_time_hour" id="quickcab_form_departure_time_hour" class="booking-input quickcab-select-input form-control" required>
<option disabled selected><?php echo esc_html__('Hour', 'quickcab'); ?></option>
<?php
// first 12 hours
for ( $i = 1; $i <= 12; $i++ ) {
?>
<option value="<?php echo sprintf('%02dAM', $i); ?>"><?php echo sprintf('%02dAM', $i);?></option>
<?php
}
// second 12 hours
for ( $i = 1; $i <= 12; $i++ ) {
?>
<option value="<?php echo sprintf('%02dPM', $i); ?>"><?php echo sprintf('%02dPM', $i);?></option>
<?php
}
?>
</select>
</div>
I'm very new to php and sql and I'm trying to set a _SESSION variable for my user_email, I know that the column name is correct and I'm pulling the other information from the session like the user_id etc correctly but cannot seem to get the email to set even though I've done it the same as my other variables. I'm also trying to use the mail() function but I'm not sure if this is set up correctly? Any help would be really appreciated!
I've tried doing the variable as a _POST one using a hidden input but that hasn't worked either.
<div>
<?php
if (isset($_POST['request_date'])) {
$user_email = $_SESSION['user_email'];
$user_id = $_SESSION['user_id'];
$first_name = $_SESSION['first_name'];
$last_name = $_SESSION['last_name'];
// $request_time = date("d-m-Y H:i:s");
$lend_status = 1;
$requested_start_date = date('Y-m-d H:i:s', strtotime($_POST['requested_start_date'] . ' ' . $_POST['requested_start_time'] . ':00:00'));
$requested_end_date = date('Y-m-d H:i:s', strtotime($_POST['requested_end_date'] . ' ' . $_POST['requested_end_time'] . ':00:00'));
$comments = $_POST['comments'];
// Declare available laptops array
$available_laptops = array();
// GET ALL LAPTOPS IN OPERATION
$STH = $DBH->prepare("
SELECT laptop_id,
laptop_name
FROM laptops
WHERE 1
");
$STH->execute(array());
while ($row = $STH->fetch()) {
// CHECK EACH LAPTOP FOR THE REQUESTED DATES
$STH2 = $DBH->prepare("
SELECT lend_id
FROM laptop_system
WHERE (
(
approved_start_date <= ?
AND approved_end_date >= ?
) OR (
approved_start_date <= ?
AND approved_end_date >= ?
) OR (
approved_start_date >= ?
AND approved_end_date <= ?
)
)
AND laptop_id = ?
");
$STH2->execute(array(
$requested_start_date,
$requested_start_date,
$requested_end_date,
$requested_end_date,
$requested_start_date,
$requested_end_date,
$row->laptop_id
));
// IF IT'S NOT BOOKED OUT, ADD TO ARRAY
if ($STH2->rowCount() < 1) {
$available_laptops[$row->laptop_id] = $row->laptop_name;
}
}
if (empty($available_laptops)) {
echo '<h3>Sorry, this date is not available.</h3>';
} else {
$STH = $DBH->prepare("
INSERT INTO laptop_system (
user_id,
first_name,
last_name,
lend_status,
requested_start_date,
requested_end_date,
comments
)
VALUES(?, ?, ?, ?, ?, ?, ?)
");
$STH->execute(array(
$user_id,
$first_name,
$last_name,
$lend_status,
$requested_start_date,
$requested_end_date,
$comments
));
echo '<h2 style="color:#D80B8C; margin-bottom:1em;">' . $first_name . ', your laptop request is now pending approval.</h2>';
$to = $user_email;
$subject = "Laptop Request";
$message = "Thank you for your laptop request for " . $requested_start_date . " - " . $requested_end_date . "It is now pending and you will be notified if it's been approved or declined.";
$message = wordwrap($message,70);
$headers = "From: Timmy and Edwardo";
mail($to,$subject,$txt,$headers);
}
} ?>
<form action="" method="post" >
<div>
<label for="requested_start_date"> Requested Start Date </label>
<input type="date" name="requested_start_date" value="<?php echo $requested_start_date; ?>">
<label for="requested_start_time">Requested start time </label>
<select name="requested_start_time" style="width:auto;margin:1em 1em 1em 0;">
<?php for ($i = 0; $i < 25; $i++) {$i = str_pad($i, 2, "0", STR_PAD_LEFT); ?>
<option value="<?php echo $i; ?>"><?php echo $i . ':00'; ?></option>
<?php } ?>
</select>
</div>
<div>
<label for="requested_end_date">Requested End Date </label>
<input type="date" name="requested_end_date" value="<?php echo $requested_end_date; ?>">
<label for="requested_end_time">Requested end time</label>
<select name="requested_end_time" style="width:auto;margin:1em 1em 1em 0;">
<?php for ($i = 0; $i < 25; $i++) {$i = str_pad($i, 2, "0", STR_PAD_LEFT); ?>
<option value="<?php echo $i; ?>"><?php echo $i . ':00'; ?></option>
<?php } ?>
</select>
</div>
<div>
<p style="margin-bottom:0;">
Please can you let us know below why you need the laptop and if there are any special requirements needed -
</p>
<input type="textarea" rows="4" cols="50" name="comments" placeholder="" required>
<input type="submit" name="request_date" value="Request Date">
<!-- <input type="hidden" name="user_email" value="<?php echo $user_email;?>" > -->
</div>
</form>
<?php
?>
</div>
I'm submitting form data and am deleting before inserting instead of checking to see if an update needs to be made. However, I get the following error:
Fatal error: Uncaught Error: Only variables can be passed by reference in /public_html/fitbit2/admin/admin_assignments.php:98 Stack trace: #0 {main} thrown in /public_html/fitbit2/admin/admin_assignments.php on line 98
This is line 98:
$stmtdel->bind_param( "ss", $Assignment, $Section[$i], $Semester, $Year );
Here is more of the code:
if ( $_POST ) {
//assign date variables
$PreStartDate = $_POST[ 'PreStartDate' ];
$PreEndDate = $_POST[ 'PreEndDate' ];
$PostStartDate = $_POST[ 'PostStartDate' ];
$PostEndDate = $_POST[ 'PostEndDate' ];
$semesterarr = array('Fall','Spring','Summer1','Summer2','Winter','May');
if (in_array($_POST['Semester'], $semesterarr)) {
$Semester = clean($_POST['Semester']);
}
if (filter_var($_POST['Year'], FILTER_VALIDATE_INT) !== FALSE) {
$Year = clean((int)$_POST['Year']);
}
//convert time format to prepare for mysql insert
$PreStartTime = clean( $_POST[ 'PreStartTime' ] );
$PreStartTime = date( "H:i:s", strtotime( "$PreStartTime" ) );
$PreEndTime = clean( $_POST[ 'PreEndTime' ] );
$PreEndTime = date( "H:i:s", strtotime( "$PreEndTime" ) );
$PostStartTime = clean( $_POST[ 'PostStartTime' ] );
$PostStartTime = date( "H:i:s", strtotime( "$PostStartTime" ) );
$PostEndTime = clean( $_POST[ 'PostEndTime' ] );
$PostEndTime = date( "H:i:s", strtotime( "$PostEndTime" ) );
//create datetime for mysql insertion
$PreStartDate = $PreStartDate . ' ' . $PreStartTime;
$PreEndDate = $PreEndDate . ' ' . $PreEndTime;
$PostStartDate = $PostStartDate . ' ' . $PostStartTime;
$PostEndDate = $PostEndDate . ' ' . $PostEndTime;
$PointsPossible = filter_var( $_POST[ 'PointsPossible' ], FILTER_SANITIZE_NUMBER_INT );
$Assignment = filter_var( $_POST[ 'Assignment' ], FILTER_SANITIZE_STRING );
$Section = $_POST[ 'SectionNumber' ];
if ( empty( $Section ) ) {
echo( "You didn't select any sections. Please click the back button in your browser to restart the process." );
exit;
} else {
//DELETE before inserting
//$stmtsel = $connection->prepare( "SELECT AssignmentID FROM Assignments WHERE Assignment=? AND SectionNumber=?" );
$stmtdel = $connection->prepare( "DELETE FROM Assignments WHERE Assignment=? AND SectionNumber=? AND Semester=? AND Year=?" );
$stmt = $connection->prepare( "INSERT INTO Assignments SET PreStartDate=?, PreEndDate=?, PostStartDate=?, PostEndDate=?, Assignment=?, PointsPossible=?, SectionNumber=?, Semester=?, Year=?" );
$N = count( $Section );
$success = '';
for ( $i = 0; $i < $N; $i++ ) {
$stmtdel = $connection->prepare("DELETE FROM Assignments WHERE Assignment=? AND SectionNumber=? AND Semester=? AND Year=?");
// 4 parameters, $sectionNumber does not need to be defined at this stage
$stmtdel->bind_param('ssss', $Assignment, $sectionNumber, $Semester, $Year);
$stmt = $connection->prepare("INSERT INTO Assignments SET PreStartDate=?, PreEndDate=?, PostStartDate=?, PostEndDate=?, Assignment=?, PointsPossible=?, SectionNumber=?, Semester=?, Year=?");
// 9 parameters
$stmt->bind_param('sssssssss', $PreStartDate, $PreEndDate, $PostStartDate, $PostEndDate, $Assignment, $PointsPossible, $sectionNumber, $Semester, $Year);
foreach ($Section as $sectionNumber) {
// $sectionNumber becomes defined here
$stmtdel->execute();
$stmt->execute();
}
$result = $stmt->get_result();
if ( $result->num_rows === 0 ) {
BodyHeader( "No Data", '', '' );
?>
<div class="alert alert-danger" role="alert">
There was a problem. None of the sections were updated.
</div>
<?php
BodyFooter();
exit;
}
$success .= $Section[$i] . " ";
}
}
}
?>
<?php //show sync message at top of page
if(isset($success)){?>
<div class="alert alert-success alert-dismissable fade show" id="flash-msg" role="alert">
You successfully updated the following sections: <?=$success; ?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<?php } ?>
<h1 class="h2">Setup Assignments</h1>
<p> </p>
<form action="admin_assignments.php" method="post">
<p style="font-weight: bold">Which section(s) would you like to apply this assignment to? </p>
<?php $stmt4 = $connection->prepare("SELECT DISTINCT SectionNumber FROM Courses WHERE SectionNumber != '' ORDER BY SectionNumber ASC
") or die($connection->error);
$stmt4->execute();
$result4 = $stmt4->get_result();
while ($row4 = $result4->fetch_assoc()):
?>
<input type="checkbox" name="SectionNumber[]" value="<?=$row4['SectionNumber'];?>" id="SectionNumber[]"><?=$row4['SectionNumber'];?>
<?php endwhile; ?>
<p> </p>
<div class="form-group has-float-label">
<select name="Assignment" class="form-control" required autofocus>
<option value="" selected>Select Assignment</option>
<?php $stmt4 = $connection->prepare("SELECT DISTINCT Assignment, AssignmentID FROM Assignments GROUP BY Assignment
") or die($connection->error);
$stmt4->execute();
$result4 = $stmt4->get_result();
while ($row4 = $result4->fetch_assoc()):
?>
<option value="<?=$row4['Assignment'];?>"><?=$row4['Assignment'];?></option>
<?php endwhile; ?>
</select>
</div>
<div class="form-group has-float-label">
<input type="text" name="PointsPossible" id="PointsPossible" value="" class="form-control" placeholder="Points Possible" required autofocus>
<label for="PointsPossible">Points Possible</label>
</div>
<div class="form-group has-float-label">
<select name="semester" id="semester" class="form-control">
<option selected="selected">--- Semester? ---</option>
<option value="summer1">Summer 1</option>
<option value="summer2">Summer 2</option>
<option value="fall">Fall</option>
<option value="spring">Spring</option>
<option value="winter">Winter Minimester</option>
<option value="may">May Minimester</option>
</select>
</div>
<div class="form-group has-float-label">
<select name="year" class="form-control">
<?php
for($i=date('Y'); $i < date('Y')+2; $i++){
echo "<option value=\"$i\">$i</option>";
}
?>
</select>
</div>
<p> </p>
<div class="form-group row">
<div class="col-sm-10">
<strong>Pre-Test</strong>
<p>Select the opening and closing dates for the Pre-Test:</p>
<p id="predates" class="input-group">
<input type="text" class="date start form-control" name="PreStartDate" placeholder="Start Date" required autofocus style="width: 150px" autocomplete="off"/>
<input type="text" class="time start form-control" name="PreStartTime" placeholder="Start Time" required autofocus style="width: 150px" autocomplete="off"/> to
<input type="text" class="date end form-control" name="PreEndDate" placeholder="End Date" required autofocus style="width: 150px" autocomplete="off"/>
<input type="text" class="time start form-control" name="PreEndTime" placeholder="End Time" required autofocus style="width: 150px" autocomplete="off"/>
</p>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<strong>Post-Test</strong>
<p>Select the opening and closing dates for the Post-Test:</p>
<p id="postdates" class="input-group">
<input type="text" class="date start form-control" name="PostStartDate" placeholder="Start Date" required autofocus style="width: 150px" autocomplete="off"/>
<input type="text" class="time start form-control" name="PostStartTime" placeholder="Start Time" required autofocus style="width: 150px" autocomplete="off"/> to
<input type="text" class="date end form-control" name="PostEndDate" placeholder="End Date" required autofocus style="width: 150px" autocomplete="off"/>
<input type="text" class="time start form-control" name="PostEndTime" placeholder="End Time" required autofocus style="width: 150px" autocomplete="off"/>
</p>
</div>
</div>
<input class="btn btn-lg btn-primary btn-block" type="submit" value="Save Changes">
</form>
What do I need to do to correct that error?
Thanks,
Tim
The problem here is that mysqli_stmt::bind_param accepts variable references. $Section[$i] does not qualify as it is a value retrieved from an array.
When executing statements in a loop, it is much more efficient to prepare and bind the statements first and only execute within the loop.
When binding, because variable references are used, the variables themselves do not need to be defined at this stage.
With that in mind, you should try this
$stmtdel = $connection->prepare("DELETE FROM Assignments WHERE Assignment=? AND SectionNumber=? AND Semester=? AND Year=?");
// 4 parameters, $sectionNumber does not need to be defined at this stage
$stmtdel->bind_param('ssss', $Assignment, $sectionNumber, $Semester, $Year);
$stmt = $connection->prepare("INSERT INTO Assignments SET PreStartDate=?, PreEndDate=?, PostStartDate=?, PostEndDate=?, Assignment=?, PointsPossible=?, SectionNumber=?, Semester=?, Year=?");
// 9 parameters
$stmt->bind_param('sssssssss', $PreStartDate, $PreEndDate, $PostStartDate, $PostEndDate, $Assignment, $PointsPossible, $sectionNumber, $Semester, $Year);
foreach ($Section as $sectionNumber) {
// $sectionNumber becomes defined here
$stmtdel->execute();
$stmt->execute();
}
When you use the bind_param function, you could only pass variables as arguments and not value. Notice in your code this $Section[$i] is not a variable but a value from array access. To fix that you need to assign a variable $SectionValue = $Section[$i] and pass that variable to bind_param.
Please forgive me, I'm just beginning to study PHP, but I'm pretty well stuck on this sample project that my tutor gave me to figure out.
The goal is to first display the local time of 4 preset timezones, then allow for the user to enter a time manually and on submit, display the time for each of the 4 times relative to the time that was manually entered.
It's also important to do a check that the user input is valid and not just pass any input on regardless of what it may be.
Something is not correct with my IF statement and no input matches, but I haven't been able to see the issue..
Would appreciate if anyone could point me in the right direction. I've been reading thru the documentation on PHP.net quite extensively and have read thru everything on dateTime already but perhaps I'm just not putting it all together yet.
<?php
$timezones = array(
'EST' => -5*3600, //equador
'UTC' => 0, //london
'CCT' => +8*3600, //beijing
'PST' => -8*3600, //los angeles
);
foreach ($timezones as $time) {
$now = time();
$now += $time;
print gmstrftime('DATE: %B %d %Y and TIME: %r <br/>',$now);
}
$nowM = date('m');
$nowD = date('d');
$nowY = date('Y');
$nowHr = date('h');
$nowMin = date('i');
$nowSec = date('s');
?>
<form action="homework2.php" method="post">
<label>Sync Timecode</label>
<input type="text" name="month" placeholder="Month <?php $nowM ?>" value="<?php $nowM ?>" />
<input type="text" name="day" placeholder="Day <?php $nowD ?>" value="<?php $nowD ?>" />
<input type="text" name="year" placeholder="Year <?php $nowY ?>" value="<?php $nowY ?>" />
<input type="text" name="hour" placeholder="Hours <?php $nowHr ?>" value="<?php $nowHr ?>" />
<input type="text" name="min" placeholder="Minutes <?php $nowMin ?>" value="<?php $nowMin ?>"/>
<input type="text" name="sec" placeholder="Seconds<?php $nowSec ?>" value="<?php $nowSec ?>"/>
<input type="submit" id="button">
</form>
<?php
$format = 'd-m-Y h:i:s';
$queryTime = $_POST['day'] . "-" . $_POST['month'] . "-" . $_POST['year'] . " " . $_POST['hour'] . ":" . $_POST['min'] . ":" . $_POST['sec'];
if (date($format,strtotime($queryTime)) == $queryTime) {
$now = new DateTime(strtotime($queryTime), new DateTimeZone('America/Los_Angeles'));
} else {
echo "You entered:" . $queryTime . "<hr style='display:block;'>";
exit;
}
$timezones = array(
'EST' => new DateTimeZone('America/Panama'),
'UTC' => new DateTimeZone('Europe/London'),
'CCT' => new DateTimeZone('Asia/Hong_Kong'),
'PST' => new DateTimeZone('America/Los_Angeles'),
);
echo "You entered:" . $now->format($format) . "<hr style='display:block;'>";
foreach ($timezones as $zone) {
$now = new DateTime($now, new DateTimeZone($zone));
print "The time in" . $zone . "is" . $now->format($format) . "<br/>";
}
?>
your fault shall be forgiven :D
Seriously, I got your code working take a look at the result here:
http://sofia.bplaced.net/homework2.php
It wasn't THAT wrong.
I don't now how reliable this page is, but this shows every change i made:
http://www.diffchecker.com/cfdm0ppc
The new working code:
<?php
$timezones = array(
'EST' => -5*3600, //equador
'UTC' => 0, //london
'CCT' => +8*3600, //beijing
'PST' => -8*3600, //los angeles
);
foreach ($timezones as $time) {
$now = time();
$now += $time;
print gmstrftime('DATE: %B %d %Y and TIME: %r <br/>',$now);
}
$nowM = date('m');
$nowD = date('d');
$nowY = date('Y');
$nowHr = date('h');
$nowMin = date('i');
$nowSec = date('s');
?>
<form action="homework2.php" method="post">
<label>Sync Timecode</label>
<input type="text" name="month" placeholder="Month <?php $nowM ?>" value="<?php $nowM ?>" />
<input type="text" name="day" placeholder="Day <?php $nowD ?>" value="<?php $nowD ?>" />
<input type="text" name="year" placeholder="Year <?php $nowY ?>" value="<?php $nowY ?>" />
<input type="text" name="hour" placeholder="Hours <?php $nowHr ?>" value="<?php $nowHr ?>" />
<input type="text" name="min" placeholder="Minutes <?php $nowMin ?>" value="<?php $nowMin ?>"/>
<input type="text" name="sec" placeholder="Seconds<?php $nowSec ?>" value="<?php $nowSec ?>"/>
<input type="submit" id="button">
</form>
<?php
$format = 'd-m-Y H:i:s';
$queryTime = $_POST['day'] . "-" . date('m',strtotime($_POST['month'])) . "-" . $_POST['year'] . " " . $_POST['hour'] . ":" . $_POST['min'] . ":" . $_POST['sec'];
if (date($format,strtotime($queryTime)) == $queryTime) {
try {
$now = new DateTime(date("c",strtotime($queryTime)));
} catch (Exception $e) {
echo $e->getMessage();
exit(1);
}
} else {
echo "You entered: " . $queryTime . "<hr style='display:block;'>";
exit;
}
$timezones = array(
'EST' => 'America/Panama',
'UTC' => 'Europe/London',
'CCT' => 'Asia/Hong_Kong',
'PST' => 'America/Los_Angeles',
);
echo "You entered: " . $now->format($format) . "<hr style='display:block;'>";
foreach ($timezones as $zone) {
$now = new DateTime(date("c",strtotime($queryTime)));
date_timezone_set($now, timezone_open($zone));
echo "The time in " . $zone . " is " . $now->format($format." \G\M\TP") . "<br/>";
}
?>
I had to alter the following things:
Your IF-statement was wrong, you compared a 12h Value to a 24H value
line 35:
"h" to "H" //altered hour-format
I expected you wanted your user to enter a month like "April" and not like "04"
line 36:
"$_POST['month']" to "date('m',strtotime($_POST['month']))" //altered month-format
You should always fetch error-exeptions - this way your code may go on in case of an error
line 36:
altered to "try{...}"
line 41:
"You entered: " //added a spacer
line 45 ot 50:
modified the array as you tried to print these in line 56 and used them as parameter in 55
line 52:
"You entered: " //added a spacer
line 55:
"DateTime()" to "date_timezone_set()" //altered the command. The new cmd is part of the same function-set
line 56:
"print" to "echo" //I like uniform code
line 56(2 and 3):
"The time in " and "is " //added spacers
line 56(4):
" \G\M\TP" //relative time to GMT
you wrote something about "...display the time for each of the 4 times relative to the time that was manually entered."
"\G\M\T" will print as "GMT"
"P" will result in the time relative to GMT$
This should work for you.
Aiyion.Prime
I've created a form that submits data to a MySQL database but the Date, Time, Year and Month fields constantly revert to the exact same date (1st January 1970) despite the fact that when I submit the information to the database the form displays the current date, time etc to me. I've already set it so that the time and date fields automatically display the current time and date. Could someone please help me with this.
Form:
<html>
<head>
<title>Ultan's Blog | New Post</title>
<link rel="stylesheet" href="css/newposts.css" type="text/css" />
</head>
<body>
<div class="new-form">
<div class="header">
<img src="images/edit-home-button.png">
</div>
<div class="form-bg">
<?php
if (isset($_POST['submit'])) {
$month = htmlspecialchars(strip_tags($_POST['month']));
$date = htmlspecialchars(strip_tags($_POST['date']));
$year = htmlspecialchars(strip_tags($_POST['year']));
$time = htmlspecialchars(strip_tags($_POST['time']));
$title = htmlspecialchars(strip_tags($_POST['title']));
$entry = $_POST['entry'];
$timestamp = strtotime($month . " " . $date . " " . $year . " " . $time);
$entry = nl2br($entry);
if (!get_magic_quotes_gpc()) {
$title = addslashes($title);
$entry = addslashes($entry);
}
mysql_connect ('localhost', 'root', 'root') ;
mysql_select_db ('tmlblog');
$sql = "INSERT INTO php_blog (timestamp,title,entry) VALUES ('$timestamp','$title','$entry')";
$result = mysql_query($sql) or print("Can't insert into table php_blog.<br />" . $sql . "<br />" . mysql_error());
if ($result != false) {
print "<p class=\"success\">Your entry has successfully been entered into the blog. </p>";
}
mysql_close();
}
?>
<?php
$current_month = date("F");
$current_date = date("d");
$current_year = date("Y");
$current_time = date("H:i");
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="month" value="<?php echo $current_month; ?>" />
<input type="text" name="date" value="<?php echo $current_date; ?>" />
<input type="text" name="year" value="<?php echo $current_year; ?>" />
<input type="text" name="time" id="time" size="5"value="<?php echo $current_time; ?>" />
<input class="field2" type="text" id="title" value="Title Goes Here." name="title" size="40" />
<textarea class="textarea" cols="80" rows="20" name="entry" id="entry" class="field2"></textarea>
<input class="field" type="submit" name="submit" id="submit" value="Submit">
</form>
</div>
</div>
</div>
<div class="bottom"></div>
<!-- //End Wrapper!-->
</body>
</html>
</html>
For some reason the posts are being submitted without a timestamp and are reverting to a default timestamp.
Sounds like your form is giving your database a very low amount of "Ticks". Notice you have an with name="date" and id="date" three times. This is most likely your problem. Change those names and ids, do use month, year, date (according to your "postback").
You have three text boxes named date. Since $_POST['month'] and $_POST['year'] are not set, strtotime() cannot figure out the correct timestamp and the SQL query looks like this:
INSERT INTO php_blog (timestamp,title,entry) VALUES ('','Title Goes Here.','')
Change the names of the input elements to what your PHP code is expecting:
<input type="text" name="month" value="<?php echo $current_month; ?>" />
<input type="text" name="date" value="<?php echo $current_date; ?>" />
<input type="text" name="year" value="<?php echo $current_year; ?>" />
After you've done this, strtotime() will be able to parse the date and insert the correct value into the query.
INSERT INTO php_blog (timestamp,title,entry) VALUES ('1272738360','Title Goes Here.','')
It could be that strtotime fails to recognize the format you are submitting your date in.
Try a classic YYYY/MM/DD format:
$timestamp = strtotime("$year/$month/$date $time");
Looks like strtotime don't understand the format you feeding to it.
Use mktime instead.
Anyway you have to always debug your code, i.e. print out the query to see if anything goes wrong.
Or consider to use mysql-supported type colymn, date or datetime
You may be confused an unix timestamp which is just number ans mysql timestamp type column which is string of 2010-05-01 00:00:00