Could somebody please help me these 2 questions, as I am having a hard time implementing this?
I am building an event calender with php, javascript, html and css using the help of a tutorial.
The calender highlights the current day as red. When a booking has been made, the day of which the booking is made, turns navy.
Question 1
This was a success, when the insert form was attached to the calender page. But due to some bizarre working of the code, the form ends up becoming designed in the same manner as the calender. So for example, if the month row is coloured yellow and the day row is colored grey, then for some reason, the form with the first row becomes yellow and the second row becomes grey. Essentially, the form style is weirdly attached to the calender style. How can I stop this from happening?
Question 2
The second query, is that in order to a avoid the above, I tried redirecting the user to the event form on a separate page. While the event was successfully added to the database, when I go back to the calender page, the booking date is not turned navy as before. I need the date to turn navy again as before and also display the booking details, as question 1 did successfully.
As you can tell, I am really stuck here, and need some help (I would really love to implement the second question/scenario) but the first one is also fine for me. Please find the code below for each question. Thank you so much any help you can provide.
Question 1
calender.php
<?php
//These are required to connect to the database
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', '');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'calender');
//This variable is used for displaying error
$error="Cannot connect";
//Connect to the database
$dbconnection=mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die($error);
mysqli_select_db($dbconnection,"calender") or die($error);
?>
<html>
<head>
<script>
//This function represents the previous button on the calender
function goPreviousMonth(month, year){
if (month == 1) {
--year;
month = 13;
}
--month
var monthstring=""+month+"";
var monthlength=monthstring.length;
if(monthlength<=1){
monthstring="0"+monthstring;
}
//This creates the URL to state the month and year.
document.location.href = "<?php $_SERVER['PHP_SELF'];?>?month="+monthstring+"&year="+year;
}
//This function represents the next button on the calender
function goNextMonth(month, year){
if (month == 12){
++year;
month = 0;
}
++month
var monthstring=""+month+"";
var monthlength=monthstring.length;
if(monthlength<=1){
monthstring="0"+monthstring;
}
//This creates the URL to state the month and year.
document.location.href = "<?php $_SERVER['PHP_SELF'];?>?month="+monthstring+"&year="+year;
}
</script>
</head>
<link rel="stylesheet" type="text/css" href="calenderfakestyle.css">
<body>
<?php
//Check the URL to see if the user has passed a variable
//This is used to check if day has a passing variable
if (isset ($_GET['day'])){
//If true, then get the day from the URL
$day = $_GET['day'];
}else{
$day = date ("d");
}
//The is used to check if month has a passing variable
if (isset ($_GET['month'])){
//If true, then get the month from the URL
$month = $_GET['month'];
}else{
$month = date ("n");
}
//The is used to check if month has a passing variable
if (isset ($_GET['year'])){
//If true, then get the year from the URL
$year = $_GET['year'];
}else{
$year = date ("Y");
}
//The calender variables
//This stores day, month and year variables within a timestamp
$currentTimeStamp = strtotime("$year-$month-$day");
//This gets the current month name
$monthName = date("F", $currentTimeStamp);
//This determines how many days there are in the current month
$numDays = date("t", $currentTimeStamp);
//This variable is used to count cells in the loop later
$counter = 0;
?>
<?php
//This code must be below the date variable
if(isset($_GET['add'])){
$title=$_POST['txttitle'];
$detail=$_POST['txtdetail'];
$eventdate=$month."/".$day."/".$year;
$sqlinsert="insert into booking (title,detail,event_date,date_added) values ('".$title."','".$detail."','".$eventdate."',now())";
$resultinsert=mysqli_query($dbconnection,$sqlinsert);
if($resultinsert){
echo "Event was successfully added";
}else{
echo "Event was not added";
}
}
?>
<table border='1'>
<tr> <td> <input class="previousbutton" type='button' value='<' name='previousbutton' onClick="goPreviousMonth (<?php echo $month.",".$year?>)"> </td>
<td colspan='5'> <span class="title"> <?php echo $monthName." ".$year; ?> </span> </td>
<td> <input class="nextbutton" type='button' value='>' name='nextbutton' onClick="goNextMonth (<?php echo $month.",".$year?>)"> </td>
</tr>
<tr>
<td>Sun</td>
<td>Mon</td>
<td>Tue</td>
<td>Wed</td>
<td>Thu</td>
<td>Fri</td>
<td>Sat</td>
</tr> <?php echo "<tr>";
//This is used to loop from 1 to the number of days in the month
for ($i = 1; $i < $numDays+1; $i++, $counter++){
//This is a timestamp for each day in the loop
$timeStamp = strtotime ("$year-$month-$i");
//This checks if if it is the first day
if($i == 1){
//This determines which day for the first date of the month
$firstDay = date ("w", $timeStamp);
//This loop is used to make a blank cell if it is not the first day
for ($j = 0; $j < $firstDay; $j++, $counter++){
//Blank space
echo "<td> </td>";
}
}
//This checks to see if the day is on the last column. If so, a new row will be made.
if($counter % 7 == 0 ){
echo "<tr></tr>";
}
$monthstring=$month;
$monthlength=strlen($monthstring);
$daystring=$i;
$daylength=strlen($daystring);
if($monthlength<=1){
$monthstring="0".$monthstring;
}
if($daylength<=1){
$daystring="0".$daystring;
}
$todaysDate=date("m/d/Y");
$dateToCompare=$monthstring. '/' . $daystring . '/' . $year;
echo "<td align='center' ";
if($todaysDate==$dateToCompare){
echo "class='today'";
}else{
$sqlCount="select * from booking where event_date='".$dateToCompare."'";
$noOfEvent= mysqli_num_rows(mysqli_query($dbconnection,$sqlCount));
if($noOfEvent>=1){
echo "class='event'";
}
}
echo "><a href='".$_SERVER['PHP_SELF']."?month=".$monthstring."& day=".$daystring."&year=".$year."&v=true'>".$i."</a></td>";
}
echo "</tr>";
?>
</table>
<?php
if(isset($_GET['v'])){
echo "<a href='".$_SERVER['PHP_SELF']."?month=".$month."& day=".$day."&year=".$year."&v=true&f=true'>Add Event</a>";
if(isset($_GET['f'])){
include("eventform.php");
}
$sqlEvent="select * from booking where event_date='".$month."/".$day."/".$year."'";
$resultEvents=mysqli_query($dbconnection,$sqlEvent);
echo "<hr>";
while($events=mysqli_fetch_array($resultEvents)){
echo "Title : ".$events['title']."<br>";
echo "Detail : ".$events['detail']."<br>";
}
}
?>
</body>
</html>
eventform.php
<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">
<table width='400px'>
<tr>
<td width='150px'>Title</td>
<td width='250px'><input type='text' name='txttitle'> </td>
</tr>
<tr>
<td width='150px'>Detail</td>
<td width='250px'> <textarea name='txtdetail'> </textarea> </td>
</tr>
<tr>
<td td colspan='2'align='center'> <input type='submit' name='btnadd' value='Add Event'> </td>
</tr>
</table>
</form>
Question 2
calender.php
<?php
//These are required to connect to the database
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', '');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'calender');
//This variable is used for displaying error
$error="Cannot connect";
//Connect to the database
$dbconnection=mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die($error);
mysqli_select_db($dbconnection,"calender") or die($error);
ob_start();
?>
<html>
<head>
<script>
//This function represents the previous button on the calender
function goPreviousMonth(month, year){
if (month == 1) {
--year;
month = 13;
}
--month
var monthstring=""+month+"";
var monthlength=monthstring.length;
if(monthlength<=1){
monthstring="0"+monthstring;
}
//This creates the URL to state the month and year.
document.location.href = "<?php $_SERVER['PHP_SELF'];?>?month="+monthstring+"&year="+year;
}
//This function represents the next button on the calender
function goNextMonth(month, year){
if (month == 12){
++year;
month = 0;
}
++month
var monthstring=""+month+"";
var monthlength=monthstring.length;
if(monthlength<=1){
monthstring="0"+monthstring;
}
//This creates the URL to state the month and year.
document.location.href = "<?php $_SERVER['PHP_SELF'];?>?month="+monthstring+"&year="+year;
}
</script>
</head>
<link rel="stylesheet" type="text/css" href="calenderfakestyle.css">
<body>
<?php
//Check the URL to see if the user has passed a variable
//This is used to check if day has a passing variable
if (isset ($_GET['day'])){
//If true, then get the day from the URL
$day = $_GET['day'];
}else{
$day = date ("d");
}
//The is used to check if month has a passing variable
if (isset ($_GET['month'])){
//If true, then get the month from the URL
$month = $_GET['month'];
}else{
$month = date ("n");
}
//The is used to check if month has a passing variable
if (isset ($_GET['year'])){
//If true, then get the year from the URL
$year = $_GET['year'];
}else{
$year = date ("Y");
}
//The calender variables
//This stores day, month and year variables within a timestamp
$currentTimeStamp = strtotime("$year-$month-$day");
//This gets the current month name
$monthName = date("F", $currentTimeStamp);
//This determines how many days there are in the current month
$numDays = date("t", $currentTimeStamp);
//This variable is used to count cells in the loop later
$counter = 0;
?>
<?php
//This code must be below the date variable
if(isset($_GET['add'])){
$title=$_POST['txttitle'];
$detail=$_POST['txtdetail'];
$eventdate=$month."/".$day."/".$year;
$sqlinsert="insert into booking (title,detail,event_date,date_added) values ('".$title."','".$detail."','".$eventdate."',now())";
$resultinsert=mysqli_query($dbconnection,$sqlinsert);
if($resultinsert){
echo "Event was successfully added";
}else{
echo "Event was not added";
}
}
?>
<table border='1'>
<tr> <td> <input class="previousbutton" type='button' value='<' name='previousbutton' onClick="goPreviousMonth (<?php echo $month.",".$year?>)"> </td>
<td colspan='5'> <span class="title"> <?php echo $monthName." ".$year; ?> </span> </td>
<td> <input class="nextbutton" type='button' value='>' name='nextbutton' onClick="goNextMonth (<?php echo $month.",".$year?>)"> </td>
</tr>
<tr>
<td>Sun</td>
<td>Mon</td>
<td>Tue</td>
<td>Wed</td>
<td>Thu</td>
<td>Fri</td>
<td>Sat</td>
</tr> <?php echo "<tr>";
//This is used to loop from 1 to the number of days in the month
for ($i = 1; $i < $numDays+1; $i++, $counter++){
//This is a timestamp for each day in the loop
$timeStamp = strtotime ("$year-$month-$i");
//This checks if if it is the first day
if($i == 1){
//This determines which day for the first date of the month
$firstDay = date ("w", $timeStamp);
//This loop is used to make a blank cell if it is not the first day
for ($j = 0; $j < $firstDay; $j++, $counter++){
//Blank space
echo "<td> </td>";
}
}
//This checks to see if the day is on the last column. If so, a new row will be made.
if($counter % 7 == 0 ){
echo "<tr></tr>";
}
$monthstring=$month;
$monthlength=strlen($monthstring);
$daystring=$i;
$daylength=strlen($daystring);
if($monthlength<=1){
$monthstring="0".$monthstring;
}
if($daylength<=1){
$daystring="0".$daystring;
}
$todaysDate=date("m/d/Y");
$dateToCompare=$monthstring. '/' . $daystring . '/' . $year;
echo "<td align='center' ";
if($todaysDate==$dateToCompare){
echo "class='today'";
}else{
$sqlCount="select * from booking where event_date='".$dateToCompare."'";
$noOfEvent= mysqli_num_rows(mysqli_query($dbconnection,$sqlCount));
if($noOfEvent>=1){
echo "class='event'";
}
}
echo "><a href='".$_SERVER['PHP_SELF']."?month=".$monthstring."& day=".$daystring."&year=".$year."&v=true'>".$i."</a></td>";
}
echo "</tr>";
?>
</table>
<?php
if(isset($_GET['v'])){
header("Location:eventform.php");
if(isset($_GET['f'])){
include("eventform.php");
}
$sqlEvent="select * from booking where event_date='".$month."/".$day."/".$year."'";
$resultEvents=mysqli_query($dbconnection,$sqlEvent);
echo "<hr>";
while($events=mysqli_fetch_array($resultEvents)){
echo "Title : ".$events['title']."<br>";
echo "Detail : ".$events['detail']."<br>";
}
}
?>
</body>
</html>
Eventform.php
<?php
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', '');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'calender');
//This variable is used for displaying error
$error="Cannot connect";
//Connect to the database
$dbconnection=mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die($error);
mysqli_select_db($dbconnection,"calender") or die($error);
//Check the URL to see if the user has passed a variable
//This is used to check if day has a passing variable
if (isset ($_GET['day'])){
//If true, then get the day from the URL
$day = $_GET['day'];
}else{
$day = date ("d");
}
//The is used to check if month has a passing variable
if (isset ($_GET['month'])){
//If true, then get the month from the URL
$month = $_GET['month'];
}else{
$month = date ("n");
}
//The is used to check if month has a passing variable
if (isset ($_GET['year'])){
//If true, then get the year from the URL
$year = $_GET['year'];
}else{
$year = date ("Y");
}
//The calender variables
//This stores day, month and year variables within a timestamp
$currentTimeStamp = strtotime("$year-$month-$day");
//This gets the current month name
$monthName = date("F", $currentTimeStamp);
//This determines how many days there are in the current month
$numDays = date("t", $currentTimeStamp);
//This variable is used to count cells in the loop later
$counter = 0;
if(isset($_GET['add'])){
$title=$_POST['txttitle'];
$detail=$_POST['txtdetail'];
$eventdate=$month."/".$day."/".$year;
$sqlinsert="insert into booking (title,detail,event_date,date_added) values ('".$title."','".$detail."','".$eventdate."',now())";
$resultinsert=mysqli_query($dbconnection,$sqlinsert);
if($resultinsert){
echo "Event was successfully added";
}else{
echo "Event was not added";
}
}
?>
<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">
<table width='400px'>
<tr>
<td width='150px'>Title</td>
<td width='250px'><input type='text' name='txttitle'> </td>
</tr>
<tr>
<td width='150px'>Detail</td>
<td width='250px'> <textarea name='txtdetail'> </textarea> </td>
</tr>
<tr>
<td td colspan='2'align='center'> <input type='submit' name='btnadd' value='Add Event'> </td>
</tr>
</table>
</form>
CSS stylesheet for both questions:
table {
position: absolute;
width: 700px;
left: 50%;
margin-left: -350px;
margin-top:-30px;
text-align: center;
border-collapse: collapse;
font-size: 20px;
}
table tr td a {
text-decoration: none;
display: block;
width:100%;
padding: 20% 0;
}
td {
width: 100px;
height: 60px;
background-color: white;
}
a:link {
color: black;
}
a:visited {
color: black;
}
td:hover {
background-color: purple;
}
.previousbutton{
width: 100px;
height: 60px;
border: none;
background-color: blue;
cursor: pointer;
font-size:20px;
}
.previousbutton:hover{
background-color: #blue;
}
.nextbutton{
width: 100px;
height: 60px;
border: none;
background-color: blue;
cursor: pointer;
font-size:20px;
}
.nextbutton:hover{
background-color: #7FFFD4;
}
.today {
background-color: red;
}
.event {
background-color: navy;
}
tr:nth-child(1) td:nth-child(2){
background-color: yellow;
}
tr:nth-child(2) td:nth-child(1n){
background-color: #D3D3D3;
}
.title {
color:black;
}
The database contains the following fields:
ID
title
detail
event_date
date_added
Question 1: your CSS is too generic, so all table related elements end up with the same style.
Ex. you define
tr:nth-child(1) td:nth-child(2){
background-color: yellow;
}
tr:nth-child(2) td:nth-child(1n){
background-color: #D3D3D3;
}
This applies to ALL tr elements in ALL tables.
If you want to apply it only to the calendar table, you could add a class name to the tr in the calendar (ex caltr), and modify your css to specify tr.caltr. Then the tr in the form would not apply this style.
You use that mechanism for .today. Only td with class="today" will end up being red, so apply the same thing to your tr elements.
Question 2: once you fix question 1, is there a need for question 2 anymore? Seems like not.
Examples:
index.html
<html>
<head>
<title>TEST</title>
<link rel="stylesheet" type="text/css" href="test2.css">
</head>
<body>
<h1>Table1</h1>
<table>
<thead>
<tr class="table1"><th>Cell1</th><th>Cell2</th></tr>
</thead>
<tbody>
<tr class="table1"><td>value1-1</td><td>Value1-2</td></tr>
<tr class="table1"><td>value2-1</td><td>Value2-2</td></tr>
<tr class="table1"><td>value3-1</td><td>Value3-2</td></tr>
</tbody>
</table>
<h1>Table2</h1>
<table>
<thead>
<tr><th>Cell1</th><th>Cell2</th></tr>
</thead>
<tbody>
<tr><td>value1-1</td><td>Value1-2</td></tr>
<tr><td>value2-1</td><td>Value2-2</td></tr>
<tr><td>value3-1</td><td>Value3-2</td></tr>
</tbody>
</table>
</body>
</html>
test2.css
/* TEST */
tr.table1:nth-child(1) td:nth-child(2){
background-color: yellow;
}
tr.table1:nth-child(2) td:nth-child(1n){
background-color: #D3D3D3;
}
Using this you will get:
See how the tr in the two tables are separate? You use the class="" attribute to differentiate between the two. You must edit your HTML and your CSS to match.
Related
I want to make an attendance list in which the date entered in the input form is put in the header of the right 3rd column. In the headers of the following columns, this date is incremented by 7 days.
I have three questions:
Why is the date not filled in the headers?
How can I insert the html table in the if statement?
How can I make the width of date columns 1 character big?
I created an input form forum.php and an action-script gen-table.php.
Inputform forum.php:
<!DOCTYPE html>
<html>
<style>
td, th {
border: 4px solid lightblue;
text-align: left;
padding: px;
}
</style>
<h2> ATTENDANCE LIST </h2>
</head>
<body>
<form action="gen-table.php" method="post">
<p>
<label for="startdate">Startdate:</label>
<input type="date" name="startdate" id="startdate" />
<input type="submit" value="Select and Activate" />
</p>
</body>
</html>
Action script gen-table.php:
<!DOCTYPE html>
<html>
<style>
td, th {
border: 4px solid lightblue;
text-align: left;
padding: px;
}
</style>
<h2> ATTENDANCE LIST </h2>
</head>
<?php
if (isset($_POST[startdate])) {
$day1 = date('d-m-Y',strtotime(startdate ."+0 Days"));
$day2 = date('d-m-Y',strtotime(startdate ."+7 Days"));
$day3 = date('d-m-Y',strtotime(startdate ."+14 Days"));
$day4 = date('d-m-Y',strtotime(startdate ."+21 Days"));
}
else
{
echo "Select startdate";
}
?>
<table>
<th>Lastname</th>
<th>Firstname</th>
<td><?php print $day1 ?> </td><td><?php echo $day2 ?></td><td><?php echo $day3 ?> </td><td><?php echo $day4 ?> </td>
</table>
</html>
Answer 1. Dates are not generating correctly. Inside strtotime() you should pass value from $_POST array.
Replace
date('d-m-Y',strtotime(startdate ."+0 Days"));
...
to
date('d-m-Y',strtotime($_POST['startdate'] . "+0 Days"));
...
Answer 2. You can dump html table with condition as follows-
<?php if(condition is true): ?>
html <table> goes here
<?php endif; ?>
Answer 3. Question is confusing, but according to my assumption you can use font size to make text bigger or use padding to give your text big space.
Sorry I'm beginner in PHP, I would like to ask for help why in localhost I perfect what I want to the process but when I upload it on our webhost it was different output from the process, same in date.
I'm from Philippines (GMT+8).
Example of what I entered in my process:
the Date today in both date input so the status will be NEW - FRESH - ACTIVE
but when I input in webhost side the status will be like DORMANT, WINBACK, INACTIVE.
Screenshot:
Localhost (which is perfect process):
Webhost view (which is not correct):
EDIT: I ADDED hongkong timezone still have problem in process in webhost
Here is my code:
<?php
date_default_timezone_set('Hongkong');
if(isset($_POST['submit']))
{
$dateRegistration = mysql_real_escape_string($_POST['dateRegistration']);
$dateStarted = mysql_real_escape_string($_POST['dateStarted']);
$dateExpiration = mysql_real_escape_string($_POST['dateExpiration']);
$accType = mysql_real_escape_string($_POST['accType']);
$subsType = mysql_real_escape_string($_POST['subsType']);
$status = mysql_real_escape_string($_POST['status']);
//declartion
$accType = "NEW";
$subsType = "FRESH";
$status = "ACTIVE";
$color = "<th style=\"color: #cccc00;\"> ";
#7f7f00
//Equation
$dateExpiration = date('Y/m/d', strtotime($dateStarted. '+ 30 days'));
//$dateRegExisting = date('Y/m/d', strtotime($dateRegistration. '+30 days'));
if (strtotime($dateRegistration)<strtotime('-30 days')) {
$accType = "EXISTING";
$subsType = "RENEWAL";
$color = "<th style=\"color: #7f7f00;\"> ";
}
if (strtotime($dateStarted)<strtotime('-30 days')) {
$subsType = "FOR RENEWAL";
$accType = "EXISTING";
$status = "INACTIVE";
$color = "<th style=\"color: red;\"> ";
}
if (strtotime($dateStarted)<strtotime('-90 days')) {
$accType = "DORMANT";
$subsType = "FOR WINBACK";
$status = "INACTIVE";
$color = "<th style=\"color: red;\"> ";
}
}
$date1 = date('Y/m/d');
echo "<br/>";
echo "<br/>";
echo "Today is: ".$date1;
?>
<html>
<head>
<title>Add New Subscriber | Customer Information System</title>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<!-- Bootstrap core CSS -->
<title>Title goes here</title>
<script src="http://cdn.jsdelivr.net/webshim/1.12.4/extras/modernizr-custom.js"></script>
<script src="http://cdn.jsdelivr.net/webshim/1.12.4/polyfiller.js"> </script>
<script>
webshims.setOptions('waitReady', false);
webshims.setOptions('forms-ext', {types: 'date'});
webshims.polyfill('forms forms-ext');
</script>
<style>
table, th, td {
border: 1px solid black;
}
#expiration {
color: red;
}
</style>
</head>
<body>
<form action="" method="POST">
<br/>
<br/>
<br/>
<label><strong>Date of Registration:</strong></label>
<input type="date" id="date" name="dateRegistration" placeholder="Date of Reg">
<label><strong>Start of Subscription:</strong></label>
<input type="date" id="date" name="dateStarted" placeholder="Start ">
<input type="hidden" id="expiration" name="dateExpiration" placeholder="Expiration" ></font>
<br/>
<br/>
<input type="submit" name="submit" value="Submit" style="margin-left: 25em;">
<br/>
<br/>
<br/>
<br/>
<table style="margin-left: 7em;">
<tr>
<th> Date of Registration </th>
<th> Start of Subscription </th>
<th> Expiration </th>
<th> Account Type </th>
<th> Subscription Type </th>
<th> Status </th>
</tr>
<tr>
<?php
echo "<th style=\"color: black;\"> ".$dateRegistration."</th>";
echo "<th style=\"color: black;\"> ".$dateStarted."</th>";
echo "<th style=\"color: black;\"> ".$dateExpiration." </th>";
echo $color.''.$accType."</th>";
echo $color.''.$subsType." </th>";
echo $color.''.$status." </th>";
?>
</tr>
</table>
</form>
</body>
</html>
May be your web host system doesn't set time to the current time, but a time somewhere in the past. You might want to check system time using:
echo date('Y-m-d H:i:s'); exit;
Put that at very first php line in your code and check if the time match with the current time, then consider change your system time.
Regards,
I have my own answer, I removed the mysql_real_escape_string if no database included.
I am working on a traffic light system. It's in a bit of a mess and it's not working the way it should.
My aim is to get the system working like so;
In the database there are dates of when a supplier's insurance is due to expire. If the date of expiry is 30 days away or less then I want these dates to be pulled through and echoed out, but others which expire after 30 days should not be shown.
At the moment it also gives the number of days until the expiry date, but this doesn't work correctly, so say today was the 2nd of May and tomorrow is the 3rd; the insurance document is due to expire on the 3rd, so it should say insurance expires tomorrow. This is currently not working correctly and I'm getting something like '2 days' till expiry instead of 'expires tomorrow'
Like wise if the insurance was due to expire today it should say expires today but its not getting the days right.
Also, i have designed diffrent coloured div tags to show as a sort of traffic light signal depending on which dates the insurance docs expire. If a document is due to expire within 30 to 20 days i want my green div to display, else if a document is due to expire in 19-7 days i want it to show as amber, if a document is due to expire 7-0 days or is over due it should be red.
Here is my code, please can someone show me how i could improve it to do what i need it to do, thanks
CODE:
<?php include 'config.php';
$data = mysql_query("SELECT *, TIMESTAMPDIFF(DAY, insurance_date, NOW()) AS expire_date FROM supplier_stats")
or die(mysql_error());
echo "<table class=\"table\" style=\"width:995px; font-family: 'Lucida Grande', Tahoma, Verdana, Arial, sans-serif;
font-size:11px;\" >
<tr>
<td style=\"width:100px;\">ID:</td><td>Company Name:</td><td>Company Reg No:</td><td>Owner:</td><td style=\"width:200px;\">Note:</td><td style=\"width:100px;\">Date:</td><td>Status:</td></tr>";
while($row = mysql_fetch_array( $data )) {
$days = $row['expire_date'] -1;
echo "<tr><td style=\"width:100px;\"><p>".$row['id'] . "</p></td>";
echo "<td style=\"width:150px;\"><p>".$row['company_name'] . "</p></td>";
echo "<td style=\"width:150px;\"><p>".$row['company_reg_number'] . "</p></td>";
echo "<td style=\"width:100px;\"><p>".$row['owner'] . "</p></td>";
if ($days > 0) {
echo "<td style=\"width:200px;\"><p>Insurance expires in <font color=\"red\">{$row['expire_date']} day(s)!</font></p></td>";
} else {
$when = $days*-1;
echo "<td style=\"width:200px;\"><p>Insurance expires";
if ($when > 1){
echo " in <font color=\"red\">{$when} days</font></p></td>";
} elseif ($when < 1) {
echo "<font color=\"red\"> tomorrow!</font></td>";
}
elseif ($when == 0)
{
echo " today!</font></p></td>";
}
echo "<td>";
echo date('d/m/Y',strtotime($row['insurance_date']));
echo"</td>";
}
if ($when >= 20){
echo "<td style=\"width:150px;\"><div class=\"green_light\"></div></td>";
}
if ($when >= 7){
echo "<td style=\"width:150px;\"><div class=\"amber_light\"></div></td>";
}
if ($when <= 7){
echo "<td style=\"width:150px;\"><div class=\"red_light\"></div></td>";
}
echo "<tr>";
}
echo "</table>"; //Close the table in HTML
?>
change the query to accurately reflect the days before the expiry_date then it should simplify the checking. The query below truncates to the day and gives accurate days_before_expires as positive numbers.
positive numbers are days before. so +1 means ends tomorrow.
zero means ends today
negative numbers means it has expired.
SELECT *, TIMESTAMPDIFF(DAY, CURRENT_DATE(), DATE(insurance_date)) AS days_before_expires FROM supplier_stats
Converted to 'mysqli'.
All the code has been tested. It implements the 'traffic light' status. I have changed the formatting code to try and make it more maintainable by using functions to calculate an 'urgency indicator'. All the formatting is now done using css.
<!DOCTYPE HTML">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF8">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title>23424062/php-expiry-date-traffic-light-system</title>
<style type="text/css">
table {
width:995px;
font-family: 'Lucida Grande', Tahoma, Verdana, Arial, sans-serif;
font-size:11px;
}
th {text-align: left; }
.width_small {
width: 100px;
}
.width_medium {
width: 150px;
}
.width_large {
width: 200px;
}
.urgency_1 {
display: inline-block;
width: 6em;
background-color: green;
color: yellow;
padding-left: 1em;
}
.urgency_2 {
display: inline-block;
width: 6em;
background-color: orange;
padding-left: 1em;
}
.urgency_3 {
display: inline-block;
width: 6em;
background-color: red;
color: yellow;
padding-left: 1em;
}
.green_light {
width: 3em;
background-color: green;
}
.amber_light {
width: 3em;
background-color: orange;
}
.red_light {
width: 3em;
background-color: red;
}
</style>
</head>
<body>
<?php
$mysqli = new mysqli('localhost', 'test', 'test', 'testmysql');
$data = $mysqli->query("SELECT *, "
." TIMESTAMPDIFF(DAY, CURRENT_DATE(), DATE(insurance_date)) AS days_before_expires, "
." DATE(insurance_date) as insurance_day "
." FROM supplier_stats order by DATE(insurance_date)")
or die(mysql_error());
?>
<table>
<tr><th class="width_small">ID:</th><th>Company Name:</th><th>Company Reg No:</th><th>Owner:</th><th class="width_large">Note:</th><th class="width_small">Date:</th><th>Status:</th></tr>
<?php while($row = $data->fetch_array()): ?>
<?php $daysLeft = $row['days_before_expires']; ?>
<?php $urgency = getUrgency($daysLeft); ?>
<?php $cssTrafficLight = selectUrgencyLit($row['days_before_expires'],
array('', 'green_light', 'amber_light', 'red_light')); ?>
<?php $cssUrgency = selectUrgencyLit($row['days_before_expires'],
array('urgency_0', 'urgency_1', 'urgency_2', 'urgency_3')); ?>
<?php $daysLeftLit = getDaysLeftLiteral($daysLeft); ?>
<tr><td class="width_small"><p><?= $row['id'] ?></p></td>
<td class="width_medium"><p><?= $row['company_name'] ?></p></td>
<td class="width_medium"><p><?= $row['company_reg_number'] ?></p></td>
<td class="width_small"><p><?= $row['owner'] ?></p></td>
<td class="width_large"><?= $daysLeftLit; ?></td>
<td class="width_small"><?= date('d/m/Y',strtotime($row['insurance_day'])) ?></td>
<td class="width_medium"><div class="<?= $cssTrafficLight?>"> </div></td>
<tr>
<?php endwhile; ?>
</table> <!-- Close the table in HTML -->
</body>
</html>
<?php
/*
* To tidy the code up and hopefully make it easier to maintain we need
* a couple of functions...
*
* How about assigning an 'urgency level' to each record depending on the
* days left before the expiry date. The level is as follows:
*
* 0 => not urgent (more than 20 days)
* 1 => need to pay attention (14 - 20)
* 2 => soon (7 - 13)
* 3 => now (0 - 6)
*/
function getUrgency($daysLeft)
{
if ($daysLeft >= 21 || $daysLeft < 0) { return 0; }
if ($daysLeft >= 14 && $daysLeft <= 20) { return 1; }
if ($daysLeft >= 7 && $daysLeft <= 13) { return 2; }
return 3;
}
// return a literal depending on the urgency
function selectUrgencyLit($daysLeft, array $litArray)
{
$urgency = getUrgency($daysLeft);
if (!empty($litArray[$urgency])) {
return $litArray[$urgency];
}
return '';
}
// return the days left literal
function getDaysLeftLiteral($daysLeft)
{
$urgency = getUrgency($daysLeft);
if ($urgency <= 0) {
return ' ';
}
$text = "Insurance Expires: <div class=\"urgency_{$urgency}\">";
// set the day literal to be shown
if ($daysLeft == 0) { $dayLit = 'today'; }
elseif ($daysLeft == 1) { $dayLit = 'tomorrow'; }
elseif ($daysLeft >= 0 && $daysLeft <= 20) { $dayLit = "in {$daysLeft} days"; }
else { $dayLit = ' '; }
return $text . $dayLit .'</div>';
}
I have a form that I would like to have display two versions of the data. I know that I can set two variables for this, but I can't figure out how to get it to insert into the postgres db. I have gotten as far populating the data and having the labels to enter in the new numbers for insertion into the table.
Here's what I have so far ...
<script>
window.onload = function() {
<?
$yesterday = date('Y-m-d', strtotime('-1 day'));
if ($_REQUEST['start'] == '') {
$_REQUEST['stores'] = array(1,2,3,7,8,9,17,18,19,23,16,11,4,5,6);
$_REQUEST['start'] = $yesterday;
} else {
$_REQUEST['stores'] = array(1,2,3,7,8,9,17,18,19,23,16,11,4,5,6);
}
$_REQUEST['submit'] = 'Get Data';
?>
}
</script>
<?
// various arrays and db connections we're going to need later
include('/home/...some_data_goes_here.../db_connect.inc');
$dbx = DB::connect('******');
$dbx->setFetchMode(DB_FETCHMODE_ASSOC);
//get the data based on the date.
$start = $_REQUEST['start'];
//$stores = array(1 => '1,177,18', 2 => '2,277,28', 3 => '3,377,38', 7 => '4,477,48', 8 => '5,577,58', 18 => '338', 19 => '50,51', 9 => '6,677,68', 17 => '8,877,818', 16 => '44,45,47', 11 => '7,770,78', 4 => '11,15,17', 5 => '22,25,27', 6 => '33,35,37');
$formstores = $_REQUEST['stores'];
foreach($stores as $sid => $pcs) {
$store_name = $db->getOne('SELECT store_name FROM stores WHERE store_id = ?', array($sid));
}
foreach($formstores as $k => $sid) {
if(empty($storeDataMain)){ //array is empty so make one
$storeDataMain = array();
}
//get the store names
$store_name = $db->getOne('SELECT store_name FROM stores WHERE store_id = ?', array($sid));
if(DB::isError($store_name)) { echo '<div class="error">Error '.$store_name->getdebuginfo().'</div>'; return; }
$tempups = $db->getOne('SELECT sum(count) FROM traffic WHERE store_id = ? AND tdate = ?', array($sid,$start));
//echo $tempups .' | ';
if(DB::isError($tempups)) { echo '<div class="error">Error '.$tempups->getdebuginfo().'</div>'; return; }
$tups = $tempups/2;
//echo $tups;
//Build array out and return it
$storeDataMain[$store_name] = array('trafficGuests' => number_format(floatval($tups),1,'.',',')); // floatval prevents the numbers from rounding to zero
}
?>
<h3 class="heading">Traffic Updates</h3>
<p>Enter dates in yyyy-mm-dd format.</p>
<script type="text/javascript" src="/css/prototype.js"></script>
<script type="text/javascript" src="/css/scriptaculous.js"></script>
<script type="text/javascript" src="/css/datepicker.js"></script>
<form name="setTraffic" method="get" action="/traffic/updateTraffic.php">
<!-- Build the table where they can input the date to be changed -->
<table>
<tr>
<th>Date</th>
</tr>
<tr>
<td>
<input type="text" name="start" id="start" value="<?=$_REQUEST['start']?>" alt="mm/dd/yyyy" onblur="if(this.value.length){valid=check_date(this.value);if(!valid){this.value='';this.focus();alert('Invalid date input');}else{this.value=valid;}}" onchange="if(this.value.length){valid=check_date(this.value);if(!valid){this.value='';this.focus();alert('Invalid date input');}else{this.value=valid;}}" onfocus="if(this.value == this.defaultValue) this.value = ''" /></td>
<script type="text/javascript">
var start_picker = new DatePicker({
relative : 'start',
language : 'en',
dateFormat : 'yyyy-mm-dd',
showDuration: 0.1,
closeEffectDuraction: 0.1,
disableFutureDate: true,
disablePastDate: false,
keepFieldEmpty : true
});
</script>
</td>
</tr>
</table>
<input class="button" type="submit" name="submit" value="Get Data" id="submit" />
</form>
<form method="post" action="">
<table>
<tr>
<th style="height: 20px; width: 165px; vertical-align: bottom;">Stores</th>
<? //build the list of stores for the headers.
foreach($storeDataMain as $k => $val){
echo '<th style="text-align: center; vertical-align: bottom;">'.$k.'</th>';
}
?>
</tr>
<tr>
<th style="height: 20px; vertical-align: bottom;">Guests for <?=$start?> </th>
<? //format and print out the traffic for each store
foreach($storeDataMain as $k => $val){
echo '<td style="text-align: center; vertical-align: bottom; font-size: 14px;">'.$val["trafficGuests"].'</td>';
}
?>
</tr>
<tr>
<th style="height: 20px; vertical-align: bottom;">Adjustment for <?=$start?></th>
<? //build the input fields identified based on store id.
foreach($formstores as $pcs) {
echo '<td><input class="newTraffic" type="number" style="width: 65px; text-align: right;" name="new_count" id="'.$pcs.'" value="'.$count.'" />'.$count.'</td>';
<script>// get the data ready for inserting into the database
if(isset($count)){
$count = $_POST['']
} else {
$count = '';
}}
if( $_POST ){
$count = $_POST["count"];
$store_id = $sid
$insertCounts = $db->query('INSERT INTO traffic (store_id, thour, tdate, count, door) VALUES ('$sid', )');
}
}
</script>
}
?>
</tr>
</table>
<input class="button" type="submit" name="submit2" value="Submit" id="submit" />
</form>
<h5 style="color: #707070;">New Traffic Counts</h5>
<table style="color: #707070;">
<tr>
<td style="height: 20px; width: 165px; font-weight: bold; vertical-align: bottom;">Stores</td>
<? //display the list of stores for the output of the new counts.
foreach($storeDataMain as $k => $val){
echo '<td style="text-align: center; width: 69px; padding: 4px; font-weight: bold; vertical-align: bottom;">'.$k.'</td>';
}
?>
</tr>
<tr>
<td style="height: 20px; vertical-align: bottom; font-weight: bold;">Guests for <?=$start?></td>
<? //format and display the NEW traffic for each store
foreach($storeDataMain as $k => $val){
$newCount = $val["trafficGuests"] + $count[$pcs];
echo '<td style="text-align: center; vertical-align: bottom; font-size: 14px;">'.$newCount.'</td>';
}
?>
</tr>
</table>
</form>
If you'd like to see what the page looks like you can go [here] (https://picasaweb.google.com/105736785937866961668/January22013#5828892865441021874) and the inputs are designed to take in the adjustment to the number, whether it's positive or negative. From there it is inserted into the DB table and added to the existing sum so that the new total can be reflected in the bottom greyed out table.
I know that this is something that may not be able to be accomplished, but if it can't I need to be able to get to the point where my data will still be entered into the table and then reflected after submit. I just can't seem to get there with my existing knowledge of code.
Please help?!
I can't comment on a question yet, but I think there are a few issues with your php. as #Anubis points out the insert statement needs work. Also, the first few lines of actual php code look like they are wrapped in a javascript event for the window loading. This is not needed as the code doesn't produce any javascript to run. This code will be run on the server during every page load anyway. There are a few other places you have <script> tags that are not needed and probably cause some errors.
I think what you want is to do is add an identifier to your post fields to help get the correct values. So when you are building your input boxes do it like this:
echo '<td><input class="newTraffic" type="number" style="width: 65px; text-align: right;" name="new_count__'.$pcs.'" id="'.$pcs.'" value="'.$count.'" />'.$count.'</td>';
And access the submitted values as follows: $_POST['new_count__' . $pcs]
You are trying to integrate two separate processes which makes your code hard to follow and more error prone. I see what you are trying to do but try putting input processing code at the top and display code towards the bottom. So in rough code/comments:
<?php //check for and process the new data
//if posted values
//process $_POST for values to add/subtract
//if(isset($_POST)) {
//if(!empty($_POST) {
switch ($_POST['submit']) {
case 'submit':
//new date selected
//get new display data
break;
case 'submit2':
//new traffic counts submitted
//for each input submitted
//add/subtract value to current database traffic value
//get new display data
break;
default:
//stuff if no submit
//get default display data
}
?>
<html>
display html data here
</html>
Your insert statement is wrong:
//, thour, tdate, count, door <- are there default values defined for theses? if not set the values
$db->query('INSERT INTO traffic (store_id) VALUES ('.$sid.')');
while programming you should use this error settings:
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
this gives you lots of errors and descriptions when something goes wrong and it makes debugging easier.
in a production environment "display_errors" should be 0!
Working off my previous question I'm trying to figure out how to achieve what I'm after.
I have an order that gets made. When the time comes to print that order, if the order has more than 25 lines/rows i need to put up from line 26 and create a new page. My question is how would I write that? I was thinking with mysql_num_rows but how can I track that?
How would I break it down, say put rows 0-24 into array1 then put rows 25-49 into array2 and so on? Then put the different arrays into while loops?
Maybe put everything into an array, then split it up?
Here's what I have right now
<?php
if (isset($_POST['CheckBox'])){
$CB = $_POST['CheckBox'];
} else {echo 'Nothing Marked'; die;}
/////////////////////////////////////////
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
#media print{ #page{margin: 5%;} }
body{
background-color: #CCC;
margin:0;
padding:0;
}
#MainWrapper{
margin:0 auto;
width:675px;
height:900px;
background-color:#3CF;
position:relative;
}
#OrderInfo{
width:200px;
height:50px;
background-color:#6C6;
float:left;
font-family:Verdana, Geneva, sans-serif;
font-size:9px;
}
#OrderInfoNotes{
width:475px;
height:50px;
background-color:#6C6;
float:right;
font-family:Verdana, Geneva, sans-serif;
font-size:9px;
}
#LineHeader{
width:675px;
background-color:#C90;
float:left;
}
.OrderLines{
font-family:Verdana, Geneva, sans-serif;
font-size:9px;
padding:0px;
}
.PBA{page-break-after: auto;}
.bigbold{ font-weight:bold; font-size:14px;}
.bigger{font-size:14px;}
</style>
</head>
<body>
<?php
///////////////////////////////////////////
foreach ( $CB as $thekey => $Order_ID )
{
$queryOrderHead = "SELECT * FROM Orders WHERE Order_ID = ".mysql_real_escape_string($Order_ID)."";
$queryOrderLines = "SELECT * FROM Order_LineDetails WHERE Order_LineDetails.Order_ID = ".mysql_real_escape_string($Order_ID)."";
//////////////////////////////////////////
if ($queryRunHead = mysql_query($queryOrderHead)){
//////////////////////////////////////////
// THIS IS THE HEADER OF THE ORDER ///////
//////////////////////////////////////////
while ($info_HEAD = mysql_fetch_array($queryRunHead))
{
$OrderDate_HEAD = $info_HEAD['OrderDate'];
$shippingservice_HEAD = $info_HEAD['shippingservice'];
$OrderNotes_HEAD = $info_HEAD['OrderNotes'];
?>
<div id="MainWrapper">
<!--START ORDERINFO INTO -->
<div id="OrderInfo">
Order ID:<span class="bigbold"><?php echo ' '.$Order_ID; ?></span><br>
<?php echo 'SHIPPER: <span class="bigbold">'.$shippingservice_HEAD.'</span>'; ?><br>
<?php echo 'ORDER DATE: '.$OrderDate_HEAD; ?>
</div>
<div id="OrderInfoNotes">
<?php echo 'NOTES: '.$OrderNotes_HEAD; ?></div>
<!--END ORDERINFO INTO -->
<hr><br>
<div id="LineHeader">
<table class="OrderLines">
<tr class="bigbold">
<td width="300"><u>Product Name:</u></td>
<td width="90"><u>UPC Code:</u></td>
<td width="50" align="right"><u>PID:</u></td>
<td width="75" align="right"><u>QTY:</u></td>
<td width="160" align="right"><u>Packer:</u></td>
</tr>
<?php
}
/////////////////////////////////////////
// THIS IS THE ORDER LINES //////////////
/////////////////////////////////////////
$queryRunLines = mysql_query($queryOrderLines);
while ($info = mysql_fetch_array($queryRunLines))
{
$ProductName_LINE = $info['ProductName'];
$qty_LINE = $info['qty'];
$Product_ID_LINE = $info['Product_ID'];
$UPC_LINE = $info['UPC'];
?>
<tr class="bigger">
<td><?php echo $ProductName_LINE; ?></td>
<td><?php echo $UPC_LINE; ?></td>
<td align="right"><?php echo $Product_ID_LINE; ?></td>
<td align="right"><?php echo $qty_LINE; ?></td>
<td></td>
</tr><tr>
<td colspan="5"><hr></td></tr>
<?php
}
///////////////////////////////////////////////////////////
// END OF ORDER LINES /////////////////////////////////////
///////////////////////////////////////////////////////////
$numRows = 0;
$numRows = mysql_num_rows($queryRunLines);
echo 'Total Rows ('.$numRows.')'
///////////////////////////////////////////////////////////
?><tr>
<td colspan="5" class="center">--- :END: ---</td>
</tr>
</table>
</div>
</div>
<p class="PBA"/>
<?php
} else {
echo mysql_error();
}
}
mysql_close($conn);
?>
</body>
</html>
From looking at your previous question, it appears you want to print the HTML page, not use pagination. Just use a counter variable:
$i = 0;
while ($info = mysql_fetch_array($queryRunLines))
{
$ProductName_LINE = $info['ProductName'];
$qty_LINE = $info['qty'];
$Product_ID_LINE = $info['Product_ID'];
$UPC_LINE = $info['UPC'];
if (!($i % 25)) {
// echo page break every 25 lines
}
// output
$i++;
}
Also take a look at CSS attributes page-break-before/page-break-after. I would also suggest using an HTML to PDF converter. They are easy to use and will make your printed documents consistent across different systems.
What you need is called pagination.
One of the way to do it is, use LIMIT clause in your query.
I would have put up here but there are hundreds of tutorials for pagination in google with good explanation. It would be better if you search by "php pagination" and learn step by step.
you can limit the number of rows returned by your query,
add LIMIT 0, 24 at the end of your query, you will get the first 25 rows.
you can have more details here
Use a variable to store how many rows you want to display and another one to store the current rows being retrieved.
Look up pagination which will give you a better idea. It may not be exactly what you what but will teach you how to limit sql results they way you want.