php expiry date traffic light system - php

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

Related

Event calender- PHP

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.

Keep values in input fields - php array

I have a php array that includes inputs for posting. It uses a counter for each array record, and this counter is applied to the name of the input to be used in performing some actions with the post - this is working great.
The issue is that I would like to keep the users' existing inputs and re-populate the input fields in the array if their post doesn't pass validation.
I have done this before with static fields, simply storing the post variable and echoing it in the "value" --- but I can't figure out how to do this when working with an array. Anyone have any ideas?
$counter = 0;
echo "<form method='post'>";
echo "<table class='mainlist' width='680'>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr height='60'>";
echo "<td class='mainlist'><input type=text name=options[$counter] autocomplete=off onclick='this.select()' class='txt'></td>";
echo "</tr>";
$counter = $counter + 1;
}
echo "</table>";
Full code per request:
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$userid = $_SESSION['login_user'];
$companyid = $_POST['companyid'];
$options = $_POST['options'];
$counter = $_POST['hiddencounter'];
$runningtotal=0;
$totaloptions = array_sum($options);
$result = mysqli_query($connection, "SELECT options_balance FROM user_options_balance WHERE user_id = '".$userid."'");
for ($i=0; $i<$counter; $i++)
{
if(empty($options[$i]))
{ /* IF NO INPUT ON OPTIONS */
/* DO NOTHING */
}
else
{
$checknewcompanies = mysqli_query($connection, "SELECT company_id FROM user_company_total_invested WHERE user_id = '".$userid."' and company_id = '" .$companyid[$i]."'");
if($checknewcompanies->num_rows == 1)
{ // do nothing
}
else
{
$runningtotal = $runningtotal + 1;
}
} /* END OF ELSE IF NOT EMPTY OPTIONS */
} /* END OF FOR LOOP */
$checkcurrentcompanies = mysqli_query($connection, "SELECT company_id FROM user_company_total_invested WHERE user_id = '".$userid."'");
$countcompanies = $checkcurrentcompanies->num_rows;
$countcheck = $runningtotal + $countcompanies;
if($countcheck <= 4)
{
while($row = mysqli_fetch_array($result))
{
$balance = $row['options_balance'];
}
if ($totaloptions>$balance)
{
$notenoughoptions= "<div style='background-color:#FF0000; border-radius: 15px; padding: 10px; color: #FFFFFF; font-size: 12px;'>Oops! You don't have enough options! Try investing less!</div>";
}
else
{
// loop through array
for ($i=0; $i<$counter; $i++)
{
if(empty($options[$i])){ /* IF NO INPUT ON OPTIONS */
/* DO NOTHING */
}
else {
if(!ctype_digit($options[$i]) or !is_numeric($options[$i])){
$charactercheck= "<div style='background-color:#FF0000; border-radius: 15px; padding: 10px; color: #FFFFFF; font-size: 12px;'>Oops! Please enter only positive numbers to invest!</div>";
}
else {
$checkcompanies = mysqli_query($connection, "SELECT company_id FROM company_main WHERE company_id = '".$companyid[$i]."'");
if($checkcompanies->num_rows != 1)
{
$companynotexist= "<div style='background-color:#FF0000; border-radius: 15px; padding: 10px; color: #FFFFFF; font-size: 12px;'>Oops! That company doesn't exist!</div>";
}
else
{
// loop through array
for ($i=0; $i<$counter; $i++)
{
if(empty($options[$i]))
{ /* IF NO INPUT ON OPTIONS */
/* DO NOTHING */
}
else
{
$query = "INSERT INTO user_company_invested(user_id, company_id, user_company_options_invested)
VALUES($userid,$companyid[$i],$options[$i])";
mysqli_query($connection, $query);
} /* END OF ELSE IF NOT EMPTY OPTIONS */
} /* END OF FOR LOOP */
$balancecheck = mysqli_query($connection, "SELECT options_balance FROM user_options_balance WHERE user_id = '".$userid."'");
while($row = mysqli_fetch_array($balancecheck))
{
$balance2 = $row['options_balance'];
}
if($balance2 > 0)
{
header('Location: user_invest.php');
}
else
{
header('Location: user_market.php');
}
} // end company check
} //end character check
} //end empty option check
} //end loop
} /* END OF NOT ENOUGH OPTIONS CHECK */
}
else
{
$toomanycompanies = "<div style='background-color:#FF0000; border-radius: 15px; padding: 10px; color: #FFFFFF; font-size: 12px;'>Oops! You can invest in a maximum of 4 companies per week. Please choose fewer companies, or invest more in some of your existing companies!</div>";
/* echo "Maximum number of companies you can invest in is 4";
echo "<br />";
echo "Companies you already are invested in: ".$countcompanies;
echo "<br />";
echo "New companies you are trying to invest in: ".$runningtotal;
echo "<br />";
echo "Total: ".$countcheck;*/
}
} /* END OF ISSET CHECK */
else
{
}
?>
<?php
$result = mysqli_query($connection,"SELECT * from company_main");
$counter=0;
echo "<form method='post'>";
echo "<table class='mainlist' width='680'>";
while($row = mysqli_fetch_array($result))
{
echo "<tr height='60'>";
echo "<td class='mainlist' width=140 align='center'>" . "<img src='".$row['company_logo']."' width='40'/>" . "</td>";
echo "<td class='mainlist' align='left' width=390 style='font-size: 15px;'>" . $row['company_name'] . "</td>";
echo "<input type=hidden name=companyid[$counter] value=" . $row['company_id'] . " />";
echo "<td class='mainlist'><input value='{$_POST['options[$counter]']}' type=text name=options[$counter] autocomplete=off onclick='this.select()' class='txt' style=' background-color: #FCFCFC;
border: solid 1px #CCCCCC;
font-size: 12px;
padding: 5px;
height: 20px;
text-align: right;'></td>";
echo "</tr>";
$counter=$counter+1;
}
echo "</table>";
echo "<input type='hidden' name='hiddencounter' value='$counter'>";
echo "
<table>
<tr>
<td width='630' height='50'></td>
<td align='right' width='60' style='color: #848580; font-size: 20px;'>Total: </td>
<td align='right' width='40' style='color: #94D90B; font-size: 20px; font-weight: bold; padding-right:20px;'><span id='sum'>0</span></td><td width='10'></td>
</tr><tr height='20px'></tr><tr>
<td width='570' align='center' style='color: #94D90B; font-size: 12px;'>";?>
<?php echo $notenoughoptions; ?>
<?php echo $charactercheck; ?>
<?php echo $toomanycompanies; ?>
<?php echo "
</td>
<td colspan='2' width='100' align='right'><input name='userinvestoptionsdynamic' type='submit' value='Invest!'></td><td width='10'></td>
</tr>
<tr height='20px'></tr>
</table>";
echo "</form>";
?>
The correct syntax is:
echo "{$arrayname($keyname)}";
So for example echo('value=' . $_POST['options'][$counter]); becomes:
echo "value={$_POST['options'][$counter]}";

generating a bar graph with php html making percentages display correctly?

Can anyone help me out im trying to do a simple code with php and html, my goal is to get my variable via database and post the number and add a % at the end but with my code it's confusing to me.
The very last one works but its hardcoded.
Click here for image.
http://i.stack.imgur.com/0Apoh.png
The yellow graph i wat to dispay at 55% and the rest wont be filled in such as the bottom graph.
<style type="text/css">
.red {background-color: red;}
.green {background-color: green;}
.yellow{background-color: yellow;}
.bar { width: 15%; border: 1px solid #000; background: grey; }
</style>
<?php
if ($percentage >= 51 && $percentage <= 74) {
echo "<div class=\"bar\" align=\"left\"><div class=\"yellow\" style=\"width: $percentage %\">$percentage test</div></div>";
} else if ($percentage >= 75){
echo "<div class=\"bar\" align=\"left\"><div class=\"green\" style=\"width: $percentage \"%\">$percentage test</div></div>";
} else if ($percentage >= 0 && $percentage <= 50) {
echo "<div class=\"bar\" align=\"left\"><div class=\"red\" style=\"width:46%\">$percentage test</div></div>";
}
?>
I cannot see how you get percentage value but I can see that you define your style in 3 different ways:
The first would produce : width: 33 px; which is somehow correct but the 2nd is wrong the right is :
echo "<div class=\"bar\" align=\"left\"><div class=\"red\" style=\"width:$percenage%\">$percentage test</div></div>";
or
echo "<div class=\"bar\" align=\"left\"><div class=\"red\" style=\"width:".$percentage."%\">$percentage test</div></div>";
This is to complete the above answer.
I forgot you can use the !important argument also.
... width:$percantage% !important;
You can not put variable inside string like that. So you should do this:
if ($percentage >= 51 && $percentage <= 74)
echo "<div class=\"bar\" align=\"left\"><div class=\"yellow\" style=\"width:". $percentage." %\">".$percentage." test</div></div>";

AJAX Tables & Inserting

I've created a "calender"-like table that updates its content via a list located in a .PHP file. It works fine, but I'd like to be able to style it better. I would like to have the text which is currently appearing in "contentContainer" under the table, appear in the cell it belongs to. As of now, if I move the div into $calender, it loads only in the first cell.
I'd also like for the row to break at 7 columns.
<script type="text/javascript">
var request;
showEvents = function(caller){
request = new XMLHttpRequest();
request.open("GET", "getevents.php?id="+caller.id, true);
request.onreadystatechange = updatePage(caller.id);
request.send(null);
};
function updatePage(elemId){
if(request.readyState == 4){
var data = request.responseText;
document.getElementById(elemId).innerHTML="<span>"+data+"</span>"
}
}
</script>
<style>
table {
width: 700px;
}
td {
border: 1px solid;
min-width: 100px;
height: 100px;
vertical-align: text-top;
text-align: right;
box-sizing:border-box;
padding: 5px;
}
</style>
</head><body>
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<th colspan="31" scope="col">Calender</th>
</tr>
<tr>
<?php
$calendar="";
for($i=1;$i<=31;$i++){
$calendar .= "<td id='".$i."' onclick='showEvents(this)'><a href='#' id='".$i."'>".$i."</a> </td>";
if (($i % 7) == 0) $calendar .= '</tr><tr>';
}
echo $calendar;
?>
</tr>
</table>
<div id="contentContainer"></div>
</body>
</html>
To get the 7 days across you're looking for, I would put this in the for loop:
if (($i % 7) == 0) $calendar .= '</tr><tr>';
As for where your events pop up in the table, make sure you pass the cell's id from showEvents to updatePage:
request.onreadystatechange = updatePage(caller.id);
…
function updatePage(elemId){
…
document.getElementById(elemId).innerHTML="<span>"+data+"</span>"
That should get you there. And to make this even more complete, I would make use of the PHP date/time functions to properly set each date in its correct place on the calendar.
Update:
I've worked on it a bit and here's what I've got. For some reason, unbeknownst to me, javascript doesn't like the two functions to be separated. That's fixed, and I've also added a day of week spacer. Here's the result:
<script type="text/javascript">
var showEvents = function(caller){
request = new XMLHttpRequest();
request.open("GET", "getevents.php?id="+caller.id, true);
request.onreadystatechange = function () {
if(request.readyState == 4){
var data = request.responseText;
document.getElementById(caller.id).innerHTML="<span>"+data+"</span>"
}
}
request.send();
};
</script>
<style>
table {
width: 700px;
border-collapse: collapse;
}
td {
border: 1px solid;
min-width: 100px;
height: 100px;
vertical-align: text-top;
text-align: right;
box-sizing:border-box;
padding: 5px;
}
</style>
</head><body>
<table>
<tr>
<th colspan="7">Calendar</th>
</tr>
<tr>
<?php
$calendar="";
$n = 0;
$month = strtotime("2012-10-01"); // Always the first of the month
$start = date('N', $month);
$days = date('t',$month);
for($i=1;$i<=$days;$i++){
$n++;
if ($n <= $start) { // '<=': week starts on Sunday; '<': week starts on Monday
$calendar .= "<td> </td>";
$i--;
} else {
$calendar .= "<td id='{$i}' onclick='showEvents(this); return false;'><a href='#' id='{$i}'>{$i}</a></td>";
}
if (($n % 7) == 0) $calendar .= '</tr><tr>';
}
echo $calendar;
?>
</tr>
</table>
<div id="contentContainer"></div>
</body>
</html>

SQL/PHP query works in PHPmyAdmin but not the site

SQL/PHP query works in PHPmyAdmin but not the site.
I notice that many have had this problem but admittedly I am not as advanced as some of the coders on this site...yet. =) I humbly request any experience you may have laying around :P Thank you.
<?php
// session_start();
// ob_start();
ini_set("display_errors", true);
error_reporting(-1);
// Connection to database.
mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('') or die(mysql_error());
?>
<?php
// Maintenance page.
$maintenance = 1; // 1 = Site Online || 0 = Site Offline
if ($maintenance == 0) {
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<head>
<style type="text/css">
body {
color:#ffffff;
background-color: #000000;
font-family: Arial, Helvetica, sans-serif;
}
</style>
</head>
<title></title>
</head>
<body>
<center><img src="images/p4flogo.png" /></center><br />
<?php
echo "<br/><br /><center>This site is currently under maintenance.</center>";
} else {
// Start of main website.
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<head>
<style type="text/css">
body {
color:#ffffff;
background-color: #000000;
font-family: Arial, Helvetica, sans-serif;
}
a:link {color: orange; text-decoration: underline; }
a:active {color: red; text-decoration: underline; }
a:visited {color: orange; text-decoration: underline; }
a:hover {color: red; text-decoration: none; }
table {
border-color: #333333;
}
th {
background-color:#ffffff;
color:#000000;
font-family: Arial, Helvetica, sans-serif;
height:30px;
}
td { font-family: Arial, Helvetica, sans-serif;
color:#ffffff;
height:35px;
}
</style>
</head>
<title></title>
</head>
<body>
<table border="0" cellspacing="1" align="center">
<tr><td>
<center><img src="images/p4flogo.png" /></center><br /><br />
<form action="" method="post">
Search for a soldier: <input type="text" name="value" size="35" /><input type="submit" value="search" /><br />
<?php
if (isset($_POST['value']) && !empty($_POST['value'])) {
$value = mysql_real_escape_string($_POST['value']);
// query to database for soldier stats
// query works in phpmyadmin but not on site.
$sql = "
SELECT
`Name`,
MAX(`Level`),
`Class`,
SUM(`Kills`),
SUM(`Deaths`),
SUM(`Points`),
SUM(`TotalTime`),
SUM(`TotalVisits`),
`CharacterID`
FROM
`Characters`
WHERE
`Name` LIKE '$value%' OR `CharacterID` LIKE '$value'
GROUP BY
`Name`,
`Class`,
`CharacterID`
ORDER BY
`Name` ASC;";
$query = mysql_query($sql);
$numrow = mysql_num_rows($query);
if ($numrow >= 1) {
echo "<br /><b>View TOP 100 Players!</b><br />";
echo "<table border=\"1\" cellspacing=\"0\" cellpadding=\"5\"> ";
echo "<th>Soldier Name</th><th>Level</th><th>Class</th><th>KDR</th><th>Kills</th><th>Deaths</th><th>Points</th><th>Hours Played</th><th>Total Visits</th><th>CharacterID</th>";
echo "<br />";
WHILE ($row = mysql_fetch_assoc($query)) {
$SoldierName = $row['Name'];
$Level = $row['Level'];
$Class = $row['Class'];
if ($Class == NULL | empty($Class)) {
$Class = '<center>n / a</center>';
}
if ($Class == 1) {
$Class = 'Assault';
}
if ($Class == 2) {
$Class = 'Recon';
}
if ($Class == 3) {
$Class = 'Medic';
}
if ($Class == 4) {
$Class = 'Engineer';
}
echo $Kills = $row['Kills'];
if ($Kills == 0) {
$Kills = 1;
}
$Deaths = $row['Deaths'];
if ($Deaths == 0) {
$Deaths = 1;
}
$Kdr = round($Kills / $Deaths, 2);
$Points = $row['Points'];
$TimePlayed = $row['TotalTime'];
if ($TimePlayed == 0) {
$TimePlayed = 1;
} else {
$TimePlayed = round(($TimePlayed / 3600), 0);
}
$TotalVisits = $row['TotalVisits'];
$CharacterID = $row['CharacterID'];
echo "<tr>";
echo "<td><b>$SoldierName</b></td>";
echo "<td>$Level</td>";
echo "<td>$Class</td>";
if ($Kdr > 3.9) {
echo "<td><font color=\"red\"><b>$Kdr</b></font></td>";
} else if ($Kdr > 2.5 && $Kdr < 4) {
echo "<td><font color=\"orange\"><b>$Kdr</b></font></td>";
} else {
echo "<td><font color=\"limegreen\">$Kdr</font></td>";
}
echo "<td>$Kills</td>";
echo "<td>$Deaths</td>";
echo "<td>$Points</td>";
echo "<td>$TimePlayed</td>";
echo "<td>$TotalVisits</td>";
echo "<td>$CharacterID</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "No player found with that name. Please try again.";
}
} else {
if (empty($_POST['value'])) {
echo "<font color=\"red\">You must enter a search value.</font>";
}
// query to p4f database for top 100 players.
$sql = "SELECT * FROM `Characters` WHERE `Points` > 1 GROUP BY `Name` ORDER BY `Points` DESC LIMIT 100;";
$query = mysql_query($sql);
echo "<h3>TOP 100 PLAYERS</h3>";
echo "<table border=\"1\" cellspacing=\"0\" cellpadding=\"5\"> ";
echo "<th></th><th>Soldier Name</th><th>Level</th><th>Class</th><th>KDR</th><th>Kills</th><th>Deaths</th><th>Points</th><th>Hours Played</th><th>Total Visits</th><th>CharacterID</th>";
// echo "Made it to loop!";
$Rank = 1;
WHILE ($row = mysql_fetch_assoc($query)) {
$SoldierName = $row['Name'];
$Level = $row['Level'];
$Class = $row['Class'];
if ($Class == NULL | empty($Class)) {
$Class = '<center>n / a</center>';
}
if ($Class == 1) {
$Class = 'Assault';
}
if ($Class == 2) {
$Class = 'Recon';
}
if ($Class == 3) {
$Class = 'Medic';
}
if ($Class == 4) {
$Class = 'Engineer';
}
$Kills = $row['Kills'];
if ($Kills == 0) {
$Kills = 1;
}
$Deaths = $row['Deaths'];
if ($Deaths == 0) {
$Deaths = 1;
}
$Kdr = round($Kills / $Deaths, 2);
$Points = $row['Points'];
$TimePlayed = $row['TotalTime'];
if ($TimePlayed == 0) {
$TimePlayed = 1;
} else {
$TimePlayed = round(($TimePlayed / 3600), 0);
}
$TotalVisits = $row['TotalVisits'];
$CharacterID = $row['CharacterID'];
echo "<tr>";
echo "<td>$Rank</td>";
echo "<td><b>$SoldierName</b></td>";
echo "<td>$Level</td>";
echo "<td>$Class</td>";
if ($Kdr > 3.9) {
echo "<td><font color=\"red\"><b>$Kdr</b></font></td>";
} else if ($Kdr > 2.5 && $Kdr < 4) {
echo "<td><font color=\"orange\"><b>$Kdr</b></font></td>";
} else {
echo "<td><font color=\"limegreen\">$Kdr</font></td>";
}
echo "<td>$Kills</td>";
echo "<td>$Deaths</td>";
echo "<td>$Points</td>";
echo "<td>$TimePlayed</td>";
echo "<td>$TotalVisits</td>";
echo "<td>$CharacterID</td>";
echo "</tr>";
$Rank++;
}
echo "</table>";
}
}
?>
</td></tr>
</table>
</body>
</html>
I'm not sure about MySQL, but I know that in SQL when you do an aggregate function, like SUM(Kills), then you can't reference the row via $row['kills']. I don't know if this is your problem, but you could try doing SUM(Kills) as 'kills' in your SELECT statement. Doing this for your aggregate SELECTs will allow you to reference them all this way.

Categories