Row conditional formatting PHP - php

I need solution for rows conditional formatting (background) based on time now and time difference, before 48 hours, 84
For example:
if in cell is today's date and time 13:00 /background color =#ffffff
if in cell value is -48 hours different color
if in cell value is -84 different color.
Here is what I have
<?php
$con = mysqli_connect("localhost", "test", "test");
if (!$con) {
die("Database Connection failed".mysqli_error());
} else {
$db_select = mysqli_select_db($con, 'test2');
if (!$db_select) {
die("Database selection failed".mysqli_error());
} else {
}
}
$records = mysqli_query($con, "SELECT * FROM test2 ORDER by user_Name");
$timenow = new DateTime();
?>
<!DOCTYPE html>
<html>
<body>
<table width="500" border="2" cellpadding="2" cellspacing='1'>
<tr bgcolor="#2ECCFA">
<th>User</th>
<th>Device</th>
<th>Last Contact</th>
</tr>
<?php
if ($records) {
while ($row = mysqli_fetch_assoc($records)) {
$calc = $timenow - $row['date'];
if ($calc > 12000) {
$rowClass = "oldOrder";
} else {
$rowClass = "normalOrder";
}
echo '<tr class="'.$rowClass.'"><td>';
echo $row['user_name'] . '';
echo '</td><td>';
echo $row['Device_ID'] . '';
echo '</td><td>';
echo $row['Last_Contact'] . '';
echo '</td></tr>';
}
}
?>
<a href=”rowClass.css” rel=”stylesheet” type=”text/css”>
</table>
Field in DB date is additional column that is set as DATETIME
I keep getting error
Notice: Object of class DateTime could not be converted to int in bla/bal line 50 that is this part
while ($row = mysqli_fetch_assoc($records)) {
$calc = $timenow - $row['date'];
if ($calc > 3) {
$rowClass = "oldOrder";
} else {
$rowClass = "normalOrder";

You can convert all the time information in the Unix Time format, using the time() function in PHP and the UNIX_TIME() function in MySQL and work this way:
<?php
$con = mysqli_connect("localhost","test","test" 'test2');
if ($con->connect_error) {
die('Connect Error: ' . $con->connect_error);
}
$records = mysqli_query($con,"SELECT *, UNIX_TIMESTAMP(date) AS u_date FROM test2 ORDER by user_Name");
$timenow = time();
?>
<!DOCTYPE html>
<html>
<body>
<table width="500" border="2" cellpadding="2" cellspacing='1'>
<tr bgcolor="#2ECCFA">
<th>User</th>
<th>Device</th>
<th>Last Contact</th>
</tr>
<?php
if ($records) {
while ($row = mysqli_fetch_assoc($records)) {
$calc = $timenow - $row['u_date'];
if ($calc > 12000) {
$rowClass = "oldOrder";
} else {
$rowClass = "normalOrder";
}
echo '<tr class="'.$rowClass.'"><td>';
echo $row['user_name'] . '';
echo '</td><td>';
echo $row['Device_ID'] . '';
echo '</td><td>';
echo $row['Last_Contact'] . '';
echo '</td></tr>';
}
}
?>
<a href="rowClass.css" rel="stylesheet" type="text/css">
</table>

You need to compare apples to apples.
If your MySQL date field is of type date/datetime, you can just pass it as argument to DateTime and compare the objects:
$dateToCompare = new \DateTime("-3 days"); // 3 days ago
while ($row = mysqli_fetch_assoc($records)) {
if ($dateToCompare > (new \DateTime($row['date']))) {
$rowClass = "oldOrder";
} else {
$rowClass = "normalOrder";

Related

php return stops the loop

good day I write a function where I want to display the records which will match on the dates last week but it only loop one time. Is there a way to return all the dates and show all the records that will match with the dates? Here is my code.
function fetch_week(){
$today = date('F d Y');
for($i = 1; $i <= 7; $i++)
{
$repeat = strtotime("-1 day",strtotime($today));
$today = date('F d Y',$repeat);
$output = '';
$conn = mysqli_connect("localhost", "root", "", "sample");
$sql = "SELECT * FROM list WHERE datee = '".$today."' ORDER BY id DESC";
$result = mysqli_query($conn, $sql);
if(empty(mysqli_num_rows($result))){
echo '<td colspan="6"><h5><center>NO RECORDS.</center></h5></td>';
}
else{
while($row = mysqli_fetch_assoc($result)){
$output .= '<tbody id="appTable">
<tr class="content" style="font-weight: normal text-align: center">
<td>'.$row["name"].'</td>
<td>'.$row["address"].'</td>
<td>'.$row["contact"].'</td>
<td>'.$row["datee"].'</td>
</tr>
</tbody>
';
}
return $output;
}
}
}
You can create an array and return that after your loop ends. Check below code:
function fetch_week() {
$today = date('F d Y');
$response = [];
for ($i = 1; $i <= 7; $i++) {
$repeat = strtotime("-1 day", strtotime($today));
$today = date('F d Y', $repeat);
$output = '';
$conn = mysqli_connect("localhost", "root", "", "sample");
$sql = "SELECT * FROM list WHERE datee = '" . $today . "' ORDER BY id DESC";
$result = mysqli_query($conn, $sql);
if (empty(mysqli_num_rows($result))) {
echo '<td colspan="6"><h5><center>NO RECORDS.</center></h5></td>';
} else {
$output = '<tbody id="appTable">';
while ($row = mysqli_fetch_assoc($result)) {
$output .= '<tr class="content" style="font-weight: normal text-align: center">
<td>' . $row["name"] . '</td>
<td>' . $row["address"] . '</td>
<td>' . $row["contact"] . '</td>
<td>' . $row["datee"] . '</td>
</tr>';
}
$output .= '</tbody>';
$response[] = $output;
}
}
return $response;
}
You need to loop through on output to print your data. But apart from all these, your code is widely open for SQL injection. Please be careful and do changes for that. Also you don't need to create tbody again and again in loop. You can do that first time only which I have changed in above code as well.
Hope it helps you.

How to create a timetable in php

I want to create a student time table having 5 subject, 5 teacher, 5 class, per day 5 hour and 5 day in a week. I have completed everything, but now the issue I am facing is if there is no data inserted for specific one day (suppose for Monday there is no class) and i am inserting data for Tuesday. Then the Tuesday data are showing on Monday.
Here's some images:
Output TimeTable(Here the No Class field's time is 2pm-3pm and day is Thursday. But it is showing in Friday and in 10am-11am)
My TimeTable database table
I want to show if there is no row inserted for a day. Then for that day data should be show as 'No Class' in front end time table.
Here I am placing my logic:
<body>
<?php include 'sidenav.php';?>
<article>
<table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;" >
<tr>
<th><b>TIME</b></th>
<th><b>Monday</b></th>
<th><b>Tuesday</b></th>
<th><b>Wednesday</b></th>
<th><b>Thursday</b></th>
<th><b>Friday</b></th>
</tr>
<tbody>
<h1>Class Wise Time Table</h1>
<?php
error_reporting(1);
session_start();
if ((isset($_SESSION['login'])) && (isset($_REQUEST['cls']))) {
$classname = $_REQUEST['cls'];
$conn = mysqli_connect("localhost", "root", "", "finaltask");
$sql = "select DISTINCT (time) as time from time_table where classname = "."'$classname'";
$rest = mysqli_query($conn, $sql);
while($t = mysqli_fetch_assoc($rest)){
$sql = "select * from time_table where classname = "."'$classname'". " AND time = '".$t['time']."'";
//print_r($sql);exit;
$res = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($res)){
//echo '<pre>'; print_r ($row);
if(($row['day']=='Monday')&&($row['time']==$t['time'])){
echo"<tr> <td>{$row['time']}</td>";
if(($row['subject']==' ')&&($row['teacher']== ' ')){
echo "<td>No Class</td>";//die('');
}else{
echo "<td>".$row['subject']."<br>".$row['teacher']."</td>";
}
}
if(($row['day']=='Tuesday')&&($row['time'])){
if(($row['subject']=='')&&($row['teacher']=='')){
echo "<td>No Class</td>";
}else{
echo "<td>".$row['subject']."<br>".$row['teacher']."</td>";
}
}
if(($row['day']=='Wednesday')&&($row['time'])){
if(($row['subject']=='')&&($row['teacher']=='')){
echo "<td>No Class</td>";
}else{
echo "<td>".$row['subject']."<br>".$row['teacher']."</td>";
}
}
if(($row['day']=='Thurshday')&&($row['time'])){
if(($row['subject']=='')&&($row['teacher']=='')){
echo "<td>No Class</td>";
}else{
echo "<td>".$row['subject']."<br>".$row['teacher']."</td>";
}
}
if(($row['day']=='Friday')&&($row['time'])){
if(($row['subject']=='')&&($row['teacher']=='')){
echo "<td>No Class</td>";
}else{
echo "<td>".$row['subject']."<br>".$row['teacher']."</td></tr>";
}
}
}
}
}
?>
</tbody>
</table>
This is my suggestion for you to go with. You can define a new array, and store the values from while loop organised by week day names and then use create another array with name of week days you want to look through, and with foreach loop you can check if you get any value for the day that is in current loop and then print No class for day with no data and time table for the day that have data, look below.
<?php
$days_data = array();
while($row = mysqli_fetch_assoc($res)){
$days_data[$row['day']] == $row;
}
if($days_data):
$week_days = array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday');
foreach($week_days as $wday){
if(!empty($days_data[$wday])){
$row_data = $days_data[$wday]; // $row_data contains all of the data from that specific day time,name,teacher and etc...
// there is data for this day
} else {
// no data for the day currently in loop
}
}
endif;
Class Wise Time Table
<table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;" >
<tr>
<th><b>TIME</b></th>
<th><b>Monday</b></th>
<th><b>Tuesday</b></th>
<th><b>Wednesday</b></th>
<th><b>Thursday</b></th>
<th><b>Friday</b></th>
</tr>
<tbody>
<?php
error_reporting(1);
session_start();
if ((isset($_SESSION['login'])) && (isset($_REQUEST['cls']))) {
$classname = $_REQUEST['cls'];
$conn = mysqli_connect("localhost", "root", "", "finaltask");
$sql = "select DISTINCT (time) as time from time_table where classname = "."'$classname'";
$rest = mysqli_query($conn, $sql);
while($t = mysqli_fetch_assoc($rest)){
$sql = "select * from time_table where classname = "."'$classname'". " AND time = '".$t['time']."'";
//print_r($sql);exit;
$res = mysqli_query($conn, $sql);
?>
<tr>
<td><?php echo $t['time'] ?></td>
<?php
$week_days = array('Monday','Tuesday','Wednesday','Thurshday','Friday');
$classes = array();
while($row = mysqli_fetch_assoc($res)) {
$classes[$row['day']] = $row;
}
foreach ($week_days as $day) {
?>
<?php if (array_key_exists($day, $classes)) { $row = $classes[$day]; ?>
<td><?php echo $row['subject'] . '<br />' . $row['teacher'] ?></td>
<?php } else { ?>
<td>No Class</td>
<?php } ?>
<?php
}
?>
</tr>
<?php
}
?>
</tbody>
</table>

Sum of while row

I'm new to php and I'm stuck. I have a report that allows a supervisor to show the working hours of the operators. I can show all the hours from the db, but I can't make a sum of all the hours. I want to display one more row that shows the total hours. How can I do that?
<?php
if(isset($_SESSION['username'])) {
$username = $_SESSION['username'];
} else {
header('Location: index.php');
die();
}
include('connect.php');
#$oret_e_punes = $_POST['oret_e_punes'];
#$grupi = $_POST['grupi'];
#$data_e_inserimit = $_POST['data_e_inserimit'];
#$data_e_inserimit_2 = $_POST['data_e_inserimit_2'];
$sql = "select grup_name from grupi";
$result = mysqli_query($dbCon, $sql);
if(!$result) {
die("Error");
}
?>
//html form
<?php
if(isset($_POST['insert'])) {
$insert = "select * from ore where grupi='$grupi' and (data between '$data_e_inserimit' and '$data_e_inserimit_2' and ore !=0)";
$result_insert = mysqli_query($dbCon, $insert);
if(!$result_insert) {
die("Error");
}
echo "<table id='table'>
<tr id='main'>
<td>Operatori</td>
<td>Grupi</td>
<td>Oret e punes</td>
<td>Data</td>
</tr>";
while ($row = mysqli_fetch_assoc($result_insert)) {
$id = $row['id'];
echo "<tr id='sub'>
<td>".$row['usr']."</td>
<td>".$row['grupi']."</td>
<td>".$row['ore']."</td> ---->working hours
<td>".$row['data']."</td>
</tr>";
$id++;
}
echo "</table>";
$_SESSION['$id'] = #$id;
}
?>
have a variable for hours before loop starts. Add in it hour of each record. After loop will end you will have your total hours
echo "<table id='table'>
<tr id='main'>
<td>Operatori</td>
<td>Grupi</td>
<td>Oret e punes</td>
<td>Data</td>
</tr>";
$hours = 0;
while ($row = mysqli_fetch_assoc($result_insert)) {
$id = $row['id'];
echo "<tr id='sub'>
<td>".$row['usr']."</td>
<td>".$row['grupi']."</td>
<td>".$row['ore']."</td> ---->working hours
<td>".$row['data']."</td>
</tr>";
$hours += $row['ore'];
$id++;
}
echo "<tr><td colspan='4'>Total</td><td>$hours</td></tr>";
echo "</table>";

PHP MYSQLI fetch Errors

At school my teacher told me a lot of thing about coding in PHP using a POSTGRES DATABASE.
But when I started to use MYSQLI Server i couldn't do a lot of thing.
First of all the functions.
My teacher told me to do this type of function
$rows = getBuildings();
if (count($elenco) == 0) {
print "<hr> No buildings here </hr>";
} else {
?>
<thead>
<tr>
<th>address</th>
<th>town</th>
<th>Manager</th>
</tr>
</thead>
<tbody>
<?php
foreach ($elenco as $riga) {
?>
<tr>
<td> <?= $row->address ?></td>
<td> <?= $row->town ?></td>
<td> <?= $row->name ?> <?= $riga->surname ?> </td>
</tr>
<?php
}
?>
</tbody>
</table>
</tbody>
</table>
<?php
}
?>
</body>
</html>
<?php
function getBuldings() {
global $db;
$sql = "select * from buildings, boss
where boss.codBo=buildings.codBu";
$rows = array();
if (!DB::isError($tab = $db->query($sql))) {
while ($row = $tab->fetchRow(DB_FETCHMODE_OBJECT)) {
$rows[] = $row;
}
} else {
die("ErrorSQL:" . $tab->getMessage());
}
return $rows;
}
?>
But to get it working in MYSQL i had to do a lot of changes. In fact there was an error in !BD::isError. I had to change the connection.php in from this one
<?php
Session_Start();
require_once("DB.php");
$db = DB::connect("pgsql:etc....");
if (DB::isError($db)) {
die("Error: " . $db->getMessage());
}
?>
to this one
<?php
$servername = "localhost";
$username = "test";
$password = "";
$dbname = "test";
// Create connection
$db = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$a = mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
echo "Connected successfully " . $a . " ";
?>
In order to show the result of the query my code had become this:
<body>
<?php
$rows = getBoss();
if (count($rows) == 0) {
print "<h2>No Boss here</h2>";
} else {
foreach ($rows as $row) {
print "<p>" . $row['name'] . "</p>";
print "<p>" . $row['surname'] . "</p>";
}
}
?>
<?php
function getBoss() {
global $db;
$sql = "select *
from test_boss
order by name, surname";
$rows = array();
if ($tab = $db->query($sql)) {
while ($row = $tab->fetch_array()) {
$rows[] = $row;
}
return $elenco;
} else {
die("Errore sql: " . $tab->getMessage() . ":" . $sql);
}
}
?>
</body>
</html>
That in facts works pretty well, but I had to change FETCH_ROW to FETCH_ARRAY.
I could not use anymore the method of posting the data from the $rows value.
<?= $row->name ?>
Because there was an error
Notice: Trying to get property of non-object
but I had to use
print "<p>".$row['name']."</p>";
What can I do in order to use the method FETCH_ROW corretly?
You can type cast the array to an object by tweaking the code slight.
if you want to retrieve an object in form of $row->name then your code will be.
while ($row= $tab->fetch_array()) {
$rows[] = (object)$row;
}
OR
while ($row= $tab->fetch_object()) {
$rows[] = $row;
}

PHP : How can get all day between tow date and but it in calender

I have two dates:
10-11-2014 and 17-11-2014
Now i would like to Get all dates between those two.
then i need to check it in calender, If its in calender, I need to color in red color
How can I do that?
This is my calender code :-
<Table class="grayBg" align="center" style="font-family: 'trebuchet MS';font-size:12px" width="288">
<caption style="font-weight:bold;padding-bottom:2px" class="black font10px">
<?php
if(file_exists('winneradmincpanel/connect.php'))
{
require_once('winneradmincpanel/connect.php');
$connect = new connect();
include 'config.php';
require_once('date/hjreedate.php');
$hijri = new HijriCalendar();
include('date/hdate.php');
$date = $hijri -> GregorianToHijri(time());
$hdate = $aday." ".$date[1].' '.$hijri ->monthName($date[0]).' '.$date[2] ." هـ";
/// get current month and year and store them in $cMonth and $cYear variables
(intval($_REQUEST["month"])>0) ? $cMonth = intval($_REQUEST["month"]) : $cMonth = date("m");
(intval($_REQUEST["year"])>0) ? $cYear = intval($_REQUEST["year"]) : $cYear = date("Y");
echo GregorianHijri::getMonthName ( $m,GregorianHijri::$GREGORIAN,$GLOBALS['lang']) . ' ' . $a;
// generate an array with all dates with events
?>
</caption>
<tr style="background:#CCCCCC">
<th>الاثنين</th>
<th>الثلاثاء</th>
<th>الاربعاء</th>
<th>الخميس</th>
<th>الجمعة</th>
<th>السبت</th>
<th>الاحد</th>
</tr>
<?php
$ts = mktime ( 1, 0, 0, $m, 1, $a );
$detail = getdate ( $ts );
echo "<tr>";
if ($detail ['wday'] == 0)
$nb = 6;
else
$nb = $detail ['wday'] - 1;
for($j = 1; $j <= $nb; $j ++)
echo "<td>";
$n = $detail ['wday'];
$valid = TRUE;
$j = 1;
$monthsArray = array();
do {
$valid = checkdate ( $m, $j, $a );
if ($valid) {
//$dateOutput = "$a-$m-$j";
$dateOutput = sprintf ( $GLOBALS['gregorianDateFormat'], $a,$m,$j);
$hijriDay = GregorianHijri::hijriDay($a,$m,$j,$GLOBALS['lang']);
$explod = explode("-",$hijriDay);
$year = $explod[1];
$day = $explod[0];
$hijriDate = GregorianHijri::hijriDate($a,$m,$j,$GLOBALS['lang'],$GLOBALS['hijriDateFormat']);
$hijriMonth = GregorianHijri::hijriMonth($a,$m,$j,$GLOBALS['lang']);
array_push($monthsArray,$hijriMonth);
$sql = "SELECT * FROM tarshoh WHERE `datedurationm`";
$sql_result = mysql_query ($sql) or die ('request "Could not execute SQL query" '.$sql);
while ($row = mysql_fetch_assoc($sql_result)) {
$events[$row["event_date"]]["dawracat"] = $row["dawracat"];
$events[$row["event_date"]]["datedurationm"] = $row["datedurationm"];
}
$currntm = $events[$row["event_date"]]["datedurationm"];
$currnth = $events[$row["event_date"]]["datedurationh"];
if(!isset($_REQUEST['day'])){
if($j == $currntm){
$bg = "#79c04b";
}else{
$bg = "";
}
}else{
if($j == $newDay){
//$bg = "#cccccc";
}else{
//$bg = "";
}
}
///////////////////////
$gregorianId = 'gregorianDate'.$j;
$hijriId = 'hijriDate'.$j;
$function = "getDateInputs('".$gregorianId."','".$hijriId."')";
if (($j + $nb) % 7 == 1)
echo "<tr>";
echo "<td align=center style='font-size:10px;cursor:pointer' bgcolor='$bg' onclick=$function class='cel-calendar-border'>
<table border='0' class='font10px' width='30' cellspacing='0' cellpadding='0' >
<tr><td align='left'><span class='black'>$j</span></td></tr>
<tr><td align='right' class='red'>$day</td></tr></table>";
echo "<input type='hidden' name=$gregorianId id =$gregorianId value='$dateOutput'>";
echo "<input type='hidden' name=$hijriId id =$hijriId value='$hijriDate'>";
$j = $j+1;
echo "</td>";
}
} while ($valid);
$monthsArray = array_unique($monthsArray);
?>
</TABLE>
<div align="center" style="font-size:10px;font-family:'trebuchet MS';padding-top:2px;padding-bottom:2px;font-weight:bold" class="red">
<?php
$i=0;
foreach ($monthsArray as $key=> $value){
$i++;
echo $value;
if ($i < count($monthsArray)){
echo " / ";
}
}
echo " ".$year;
}
?>
</div>
and i get this tow date by this query :-
$sql = "SELECT * FROM tarshoh WHERE `datedurationm`";
$sql_result = mysql_query ($sql) or die ('request "Could not execute SQL query" '.$sql);
while ($row = mysql_fetch_assoc($sql_result)) {
$events[$row["event_date"]]["datestartm"] = $row["datestartm"];
$events[$row["event_date"]]["dateendm"] = $row["dateendm"];
}
And the calender here :-
echo "<tr>";
echo "<td align=center style='font-size:10px;cursor:pointer' bgcolor='$bg' onclick=$function class='cel-calendar-border'>
<table border='0' class='font10px' width='30' cellspacing='0' cellpadding='0' >
<tr><td align='left'><span class='black'>$j</span></td></tr>
<tr><td align='right' class='red'>$day</td></tr></table>";
echo "<input type='hidden' name=$gregorianId id =$gregorianId value='$dateOutput'>";
echo "<input type='hidden' name=$hijriId id =$hijriId value='$hijriDate'>";
$j = $j+1;
echo "</td>";

Categories