Good Morning, I have Written a Dashboard for work written in PHP and Javascript. It pulls Data from our database and shows events in Divs with a class of Dash, Showing a Variable of $nextupdate, I need to write some Js that will compare the DateTime Now and if the $nextupdate variable time is past then i need to change the Div Class to .overdue, I am struggling to figure out how would be the best way to solve this
any help would be much appreciated
Regards
Steve
Try this :
$nextupdate; // got from the database
$now = date();
$divClass = "";
if(strtotime($now) > strtotime($nextupdate) ){
$divClass="overdue";
}else{
$divClass="whatever";
}
and then :
<div class="<?php echo $divClass; ?>"></div>
That works Great for changing the Div colour to red when overdue, Although i didnt explain that i have Multiple Divs...
Here is my Code for the Div
//Gather all Posted HPi tickets raised
$sql = "Select *
From hpi_calls
where status!='Closed'
and (Priority='P1' or Priority='M1')
order by NextUpdate Asc";
$result = $conn->query($sql);
$statuslist = "";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$SR = $row["SR"];
$Priority = $row["Priority"];
$Customer = $row["Customer"];
$BDescription = $row["BDescription"];
$Team = $row["Team"];
$Engineer = $row["Engineer"];
$OpenTime = $row["OpenTime"];
$Status = $row["Status"];
$LastUpdate = $row["LastUpdate"];
$NextUpdate = $row["NextUpdate"];
$Owner = $row["Owner"];
$FDescription = $row["FDescription"];
$ASites = $row["ASites"];
$LoggingTeam = $row["LoggingTeam"];
$OwningTeam = $row["OwningTeam"];
$FUpdate = $row["FUpdate"];
$Supplier = $row["Supplier"];
$NextUpdate;
$now = date("Y-m-d H:i");
$divClass = "";
if(strtotime($now) > strtotime($NextUpdate) ){
$divClass="Overdue";
}else{
$divClass="Dash";
}
$statuslist .= '<div id="status_'.$SR.'" class=" '.$divClass.'"><h2>'
.$SR.'</h2><h2>'.$Customer.'</h2><h2>'.$Priority.'</h2> - '.$Status.'<br><h2>Next Update Due:<br>'.$NextUpdate.'</h2></div>';
}
}
The above is the Complete code for selecting from the DB and posting to the Divs
Regards
Steve
Related
I have a simple section in which I am displaying data from the database, my database looks like this.
Now I have four buttons looks like this
When a user clicks one of the above buttons it displays this
So now when user eg select construction and next select eg Egypt' in the console and clicks buttonconfirmdisplays [855,599075], user can select multiple countries, this works as expected forconstruction ,power,oil`,
Now I want if user eg clicks All available industries button in those four buttons and next select eg Egypt and click confirm it should display
the sum of egypt total projects in construction, oil, power sector 855+337+406 =1598 and the sum of total budgets in both sectors 1136173
Here is my solution
HTML
<div id="interactive-layers">
<div buttonid="43" class="video-btns">
<span class="label">Construction</span></div>
<div buttonid="44" class="video-btns">
<span class="label">Power</span></div>
<div buttonid="45" class="video-btns">
<span class="label">Oil</span></div>
<div buttonid="103" class="video-btns">
<span class="label">All available industries</span>
</div>
</div>
Here is js ajax
$("#interactive-layers").on("click", ".video-btns", function(){
if( $(e.target).find("span.label").html()=="Confirm" ) {
var selectedCountries = [];
$('.video-btns .selected').each(function () {
selectedCountries.push( $(this).parent().find("span.label").html() ) ;
});
if( selectedCountries.length>0 ) {
if(selectedCountries.indexOf("All available countries")>-1) {
selectedCountries = [];
}
} else {
return;
}
var ajaxurl = "";
if(selectedCountries.length>0) {
ajaxurl = "data.php";
} else {
ajaxurl = "dataall.php";
}
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
countries: selectedCountries.join(","),
sector: selectedSector
},
success: function(result){
console.log(result);
result = JSON.parse(result);
$(".video-btns").each(function () {
var getBtn = $(this).attr('buttonid');
if (getBtn == 106) {
var totalProjects = $("<span class='totalprojects'>"+ result[0] + "</span>");
$(this).append(totalProjects)
}else if(getBtn ==107){
var resultBudget = result[1]
var totalBudgets = $("<span class='totalbudget'>"+ '$m' +" " + resultBudget +"</span>");
$(this).append( totalBudgets)
}
});
return;
}
});
}
});
Here is php to get all dataall.php
$selectedSectorByUser = $_POST['sector'];
$conn = mysqli_connect("localhost", "root", "", "love");
$result = mysqli_query($conn, "SELECT * FROM meed");
$data = array();
$wynik = [];
$totalProjects = 0;
$totalBudget = 0;
while ($row = mysqli_fetch_array($result))
{
if($row['Sector']==$selectedSectorByUser ) {
$totalProjects+= $row['SumofNoOfProjects'];
$totalBudget+= $row['SumofTotalBudgetValue'];
}
}
echo json_encode([ $totalProjects, $totalBudget ] );
exit();
?>
Here is data.php
<?php
$selectedSectorByUser = $_POST['sector'];
$countries = explode(",", $_POST['countries']);
//var_dump($countries);
$conn = mysqli_connect("localhost", "root", "", "meedadb");
$result = mysqli_query($conn, "SELECT * FROM meed");
$data = array();
$wynik = [];
$totalProjects = 0;
$totalBudget = 0;
while ($row = mysqli_fetch_array($result))
{
if($row['Sector']==$selectedSectorByUser && in_array($row['Countries'],$countries ) ) {
// array_push($data, $row);
$totalProjects+= $row['SumofNoOfProjects'];
$totalBudget+= $row['SumofTotalBudgetValue'];
}
}
// array_push($wynik, $row);
echo json_encode([ $totalProjects, $totalBudget ] );
//echo json_encode($data);
exit();
?>
Now when the user clicks All available industries btn and selects a country I get [0,0] on the console.
What do I need to change to get what I want? any help or suggestion will be appreciated,
in you dataAll.php
If you have select All available industries
you shold not check for sector because you need all sector (eventually you should check for countries )
so you should avoid the check for this condition
<?php
$conn = mysqli_connect("localhost", "root", "", "love");
$result = mysqli_query($conn, "SELECT * FROM meed");
$data = [];
$wynik = [];
$totalProjects = 0;
$totalBudget = 0;
while ($row = mysqli_fetch_array($result)) {
$totalProjects += $row['SumofNoOfProjects'];
$totalBudget += $row['SumofTotalBudgetValue'];
}
echo json_encode([$totalProjects, $totalBudget]);
You can use the SQL JOIN operator, or in this case an implicit join would be cleanest:
$result = mysqli_query($conn, "SELECT * FROM construction, power, oil_and_gas, industrial WHERE construction.Countries = power.Countries AND power.Countries = oil_and_gas.Countries AND oil_and_gas.Countries = industrial.Countries");
You need the WHERE conditions so it knows how the rows of each different table are related to each other. You can shorten it a bit with aliases for the tables:
$result = mysqli_query($conn, "SELECT * FROM construction as C, power as P, oil_and_gas as G, industrial as I WHERE C.Countries = P.Countries AND P.Countries = G.Countries AND G.Countries = I.Countries");
In this case, however, I think you may want to consider changing the structure of your database. It seems like you repeat columns quite a bit across them. Perhaps these can all be in a single table, with a "type" column that specifies whether it's power, construction, etc. Then you can query just the one table and group by country name to get all your results without the messy joins across 4 tables.
The single table looks OK.
(The rest of this Answer is not complete, but might be useful.)
First, let's design the URL that will request the data.
.../foo.php?industry=...&country=...
But, rather than special casing the "all" in the client, do it in the server. That is, the last button for industry will generate
?industry=all
and the PHP code will not include this in the WHERE clause:
AND industry IN (...)
Similarly for &country=all versus &country=egypt,iran,iraq
Now, let me focus briefly on the PHP:
$wheres = array();
$industry = #$_GET['industry'];
if (! isset($industry)) { ...issue error message or use some default... }
elseif ($industry != 'all') {
$inds = array();
foreach (explode(',', $industry) as $ind) {
// .. should test validity here; left to user ...
$inds[] = "'$ind'";
}
$wheres[] = "industry IN (" . implode(',', $inds) . )";
}
// ... repeat for country ...
$where_clause = '';
if (! empty($wheres)) {
$where_clause = "WHERE " . implode(' AND ', $wheres);
}
// (Note that this is a generic way to build arbitrary WHEREs from the data)
// Build the SQL:
$sql = "SELECT ... FROM ...
$where_clause
ORDER BY ...";
// then execute it via mysqli or pdo (NOT mysql_query)
Now, let's talk about using AJAX. Or not. There were 2 choices:
you could have had the call to PHP be via a GET and have that PHP display a new page. This means that PHP will be constructing the table of results.
you could have used AJAX to request the data. This means that Javascript will be constructing the data of results.
Which choice to pick probably depends on which language you are more comfortable in.
Hi i'm making a weekly calendar with php and I wanna put events in the calendar like this example, but I don't know how to echo the events in the calendar at the correct part of the day.
This is the code I use to echo the calendar :
<?php
$dt = new DateTime;
if (isset($_GET['year']) && isset($_GET['week'])) {
$dt->setISODate($_GET['year'], $_GET['week']);
}else{
$dt->setISODate($dt->format('o'), $dt->format('W'));
}
$year = $dt->format('o');
$week = $dt->format('W');
?>
Vorige week
Volgende week
<?php
$getDatum = $conn->prepare("
SELECT DISTINCT D.DocentID, CONCAT(D.Voornaam, ' ', D.Achternaam) AS Docentnaam, D.Telefoonnummer, D.Mobiel, D.Email, CO.DatumBegin, CO.DatumEind, O.Onderdeelnaam
FROM docenten D
INNER JOIN psentity PE ON D.DocentID = PE.psid
INNER JOIN docentonderdelen DO ON D.DocentID = DO.DocentID
INNER JOIN cursusonderdelen CO ON DO.OnderdeelID = CO.OnderdeelID
RIGHT JOIN onderdelen O ON CO.OnderdeelID = O.OnderdeelID
WHERE O.OnderdeelID = 6
AND CO.DatumBegin AND CO.DatumEind BETWEEN '2018-12-10' AND '2019-10-10'
AND PE.deleted = 0
LIMIT 3");
$getDatum->bindParam(':OID', $OID, PDO::PARAM_STR);
$getDatum->bindParam(':BeginDatum', $BeginDatum, PDO::PARAM_STR);
$getDatum->bindParam(':Einddatum', $Einddatum, PDO::PARAM_STR);
$getDatum->execute();
$docenten = array();
while ($row = $getDatum->fetch(PDO::FETCH_ASSOC))
{
$docenten[] = $row;
}
Pastebin link to code
Because the code would otherwise be to long. I hope the information I gave is sufficient.
You can store the time for event in DatumBegin or in a new column (suppose eventTime with format (H:i:s)) and create three arrays according to time and then iterate them in different tr
$morningTime = date("00:00:00");
$afternoonTime = date("12:00:00");
$eveningTime = date("17:00:00");
$morningEvents = [];
$afternoonEvents = [];
$eveningEvents = [];
while ($row = $getDatum->fetch(PDO::FETCH_ASSOC))
{
$dyDate = date($row['eventTime']);
if($dyDate<$afternoonTime){ // store "Morning Event";
$morningEvents[] = $row;
}
if($dyDate>=$afternoonTime && $dyDate<$eveningTime){ // store "Afternoon Event";
$afternoonEvents[] = $row;
}
if($dyDate>=$eveningTime){ // store "Evening Event";
$eveningEvents[] = $row;
}
}
I've created a search page that sends results to a table with the ability to click on a specific record which then opens another page in the desired format.
I'd like to do is be able to open different formatted pages based on the data returned in the search query but I'm having a bit of trouble pulling it all together.
Here's the PHP used to request and retrieve the data from the database, as well as populate it in a table where each record can be selected and used to populate a planner page with all the proper formatting:
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
Now the fun part. I want to open different pages based on the information contained in the record. I've got it working for the pkey variable by itself with a single javascript function. However, if I want to open a differently formatted page using the same function using if, else statements, the table only populates with the link page based on the last record compared. Here is my attempt to get the JavaScript with the if, else statements working but it only uses the format of the last record that's compared.
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
} else {
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}
How do I get the 'Get Planner' button to open the correctly formatted planner page based on the users specific information?
To make things easier I'd suggest the following:
Do the logic already in php when generating the html-table (and the link).
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
if($rsv) { // thats basicly the same as !=0
$target='../php/plannerR.php'
} else {
$target='../php/planner.php'
}
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td>";
echo "<td>".$row['rank']."</td><td>".$row['ment1']."</td>";
echo "<td><a class='button styleIt' href='".$target."?pkey=".$pkey."&rsv=".$rsv."'>Get Planner</a></td></tr>";
}
If you wanna stick to your js solution (which is more hassle unless you really need it) you can of course go with the solution from my comments that you already successfully implemented (and posted as answer so others can see the implementetion).
Thanks to Jeff I played around a bit with bringing both variables into the function and got it to work. Final code below.
$search = $_POST['search'].'%';
$ment = $_POST['ment'];
$stmt = $link->prepare("SELECT lname, fname, rank, reserve, ment1, pkey FROM planner WHERE lname LIKE ? AND ment1 LIKE ? ORDER BY lname, fname");
$stmt->bind_param('ss', $search, $ment);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th><th>Rank</th><th>Mentor Group</th><th></th></tr>";
while($row = $result->fetch_assoc()) {
$rsv = $row['reserve'];
$pkey = $row['pkey'];
echo "<tr><td>".$row['lname']."</td><td>".$row['fname']."</td><td>".$row['rank']."</td><td>".$row['ment1']."</td><td><button onClick=getPlanner('".$pkey."','".$rsv."');>Get Planner</button></td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
var pkey = <?php echo json_encode($pkey); ?>;
var rsv = <?php echo $rsv ?>;
//var check = document.write(rsv);
function getPlanner(pkey, rsv) {
if(rsv != 0){
var plan = window.open("../php/plannerR.php?pln=" + pkey);
}
else{
var plan = window.open("../php/planner.php?pln=" + pkey);
}
}
I'm creating a system, and in part of it, you have to be able to remove employees from their Saturday shifts. To do this, you click on an icon which calls the JavaScript function "removeEmpFromSaturday" and submits the corresponding parameters.
In that Script, it should then update values via an Ajax request, that should update my database and remove the employee from his/her Saturday shift.
However, the PHP page that I point to, is never actually called/requested ("Evidenced by Alerts on the PHP page").
I'm relatively new to AJAX and perhaps my syntax is entirely wrong for this function, so any additional pointers would be greatly appreciated.
For reference, when I alert any of the values "id, loc, week, year" they all give me the correct values I'm expecting, so it isn't a problem there.
Below is the code where I believe the problem lies:
<script>
function removeEmpFromSaturday(id, loc, week, year){
xhttp = new XMLHttpRequest();
xhttp.open("GET", "includes/ajax/remove_emp_from_saturday.php?e_id=" + id +
"&location=" + loc + "&week=" + week + "&year=" + year, false);
xhttp.send();
resetPlanner();
}
</script>
The PHP code I'm pointing too:
<?php require_once dirname(__FILE__)."/../admin_header.php" ;?>
<script>alert("STARTED");</script>
<?php
if(isset($_REQUEST['e_id'])){
$emp_id = escape($_REQUEST['e_id']);
$loc = escape($_REQUEST['location']);
$week = escape($_REQUEST['week']);
$year = escape($_REQUEST['year']);
$query = "SELECT e_hp_daily_pat FROM employees WHERE e_id = '{$emp_id}' ";
$get_hp_daily_pat_query = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($get_hp_daily_pat_query);
$e_hp_daily_pat = escape($row['e_hp_daily_pat']);
$query = "SELECT * FROM slots WHERE s_location = '{$loc}' AND s_day = '6'
AND s_week = '{$week}' AND s_year = '{$year}' ";
$get_emps_query = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($get_emps_query);
$s_real_sub = escape($row['s_real_sub']);
$s_emps = escape($row['s_emps']);
$s_emps = explode(";", $s_emps);
$process = false;
$e_match = 0;
foreach($s_emps as $emp){
if($emp == $emp_id){
unset($s_emps[$e_match]);
$process = true;
}
$e_match++;
}
if($process == true){
$s_emps = implode(";", $s_emps);
$s_real_sub -= $e_hp_daily_pat;
$query = "UPDATE slots SET s_emps = '{$s_emps}', s_real_sub = '{$s_real_sub}' WHERE s_location = '{$loc}' AND s_day = '6' AND s_week = '{$week} AND s_year = '{$year}' ";
$set_emps_query = mysqli_query($connection, $query);
}
}
?>
<script>alert("COMPLETE");</script>
And please before anyone mentions it, I understand I am not binding my parameters and that is slightly outdated in mysqli, I will update that later.
You have an error in your update query:
$query = "UPDATE slots SET s_emps = '{$s_emps}', s_real_sub = '{$s_real_sub}' WHERE s_location = '{$loc}' AND s_day = '6' AND s_week = '{$week} AND s_year = '{$year}' ";
You're missing a "'" after the s_week
$query = "UPDATE slots SET s_emps = '{$s_emps}', s_real_sub = '{$s_real_sub}' WHERE s_location = '{$loc}' AND s_day = '6' AND s_week = '{$week}' AND s_year = '{$year}' ";
General advice: to debug your php code, try not to use <script>alert("")</script>, but instead use echo calls from within the php directly.
This will assure you that the php is found and parsed.
I'd like to find a way of having a single page in the root of each of my web sections to hold all of the databae queries I'm calling.
I'm using a little script .....
<script type="text/javascript">
$(function() {
var availableTags = <?php include('fn-search-em.php'); ?>;
$("#quick-add").autocomplete({
source: availableTags,
autoFocus:true
});
});
</script>
.... to do SQL searches that appear as the user is typing. Similar to this ....
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
$result = mysqli_query($conn, $sql);
$results_list = array();
while($row = mysqli_fetch_array($result))
{
$colour_id = $row['id'];
$range_name = $row['range_name'];
$range_colour = $row['colour'];
$colour_code = $row['code'];
$p1 = $row['piece_size_1'];
$p2 = $row['piece_size_2'];
if($p1 > 1){
$p_mark = 'x';
}
else {
$p_mark = '';
}
$results_list[] = $range_name.' ('.$range_colour.' '.$colour_code.' '.$p1.$p_mark.$p2.') ID:'.$colour_id;
}
echo json_encode($results_list);
Echos a list in the form of a JSON array back to the text box and voila, a list. However, the site I'm working on at the moment has about 20 search boxes for various reasons scattered around (user request), does this mean I have to have 20 separate php function pages, each with their own query on, or can a single page be used?
I suspect the java needs modifying a little to call a specific function on a page of multiple queries, but I'm not good with Java, so some help would be greatly appreciated.
I did initially try adding ?action= to the end of the PHP address in the Java script, hoping a GET on the other end would be able to separate the PHP end into sections, but had no luck.
You need to change <?php include('fn-search-em.php'); ?>; to <?php $action = 'mode1'; include('fn-search-em.php'); ?>;.
Then in your fn-search-em.php file, use the $action variable to determine what kind of MySQL query you make.
For example:
if ($action == 'mode1')
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
else
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'mode1' AND deleted = 'no'";
You can do this with by creating a php file with a switch statement to control what code is executed during your Ajax call:
JS:
$.ajax({url: 'ajax.php', method: 'POST', async:true, data: 'ari=1&'+formData,complete: function(xhr){ var availableTags = JSON.parse(xhr.responseText);}});
PHP:
<?php
switch($_REQUEST['ari']){
case 1:
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
$result = mysqli_query($conn, $sql);
$results_list = array();
while($row = mysqli_fetch_array($result)){
$colour_id = $row['id'];
$range_name = $row['range_name'];
$range_colour = $row['colour'];
$colour_code = $row['code'];
$p1 = $row['piece_size_1'];
$p2 = $row['piece_size_2'];
if($p1 > 1){$p_mark = 'x';}
else { $p_mark = ''; }
$results_list[] = $range_name.' ('.$range_colour.' '.$colour_code.' '.$p1.$p_mark.$p2.') ID:'.$colour_id;
}
echo json_encode($results_list);
break;
case 2:
// another SQL Query can go here and will only get run if ARI == 2
break;
}
?>
This allows you to keep multiple AJAX handlers in the same file, you just need to pass the index for the desired handler when you make calls to the PHP file or nothing will happen.