How to put events in a weekly calendar - javascript

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

Related

Get data from database using php,ajax

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'>"+ '&#36m' +" " + 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.

select data from database without refreshing the page in php

While getting data from the database it is alerting 0000:00:00 while in the database it is inserting write date
<?php
$query = "select * from Reply t1 inner join users t2 on t1.UserId = t2.UserId where comment = '$commentid'";
$run1 = mysqli_query($mysqli,$query);
$numberRows = mysqli_num_rows($run1);
while($row1 = mysqli_fetch_array($run1))
{
$Reply = $row1['Reply'];
$UserId = $row1['UserId'];
$UserName = $row1['UserName'];
$date1 = $row['Date'];
echo "<script>alert('$date1')</script>";
$ageDate1 = time_elapsed_string($date1);
echo "<script>alert('$ageDate1')</script>";
?>

AJAX calling Does Not Update Database

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.

loop inside a loop with different mysql in php

Objective: We need that it find registered people and shows which countries had visited like In this image
We need to make a loop that creates php objects (The artists), with its own classes. This objetcs will come from a DataBase (mysql). For each of this objects, we need that it looks in the DataBase which rows are related with it (countries), and make it an php objetc too, with its own classes (Its own design with CSS, HTML)
We already tryed Angular with ng-bind-html so it could read HTML tags and its CSSs, but it only took the first loop, and the second one just didn't appeard. We tryed while inside another while, but I don't know what happens, but it only takes the first one.
The idea to make a loop this way is to hide countries while the user doesn't want to see them. If they click on the artist name, it will shows up the countries. But this is another story, we think we will use CSS for that.
I'll put the code I tryed to use for Angular, just in case someone have an idea with Angular.js.
Thank you very much for reading this. Best Wishes and Best Regards !
$data;
$data['info'] = "";
$id = $_POST['id'];
if (isset($_POST['id'])){
$dsn = 'mysql:dbname=ec;host=localhost;port=3306';
$user = 'root';
$password = '';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$connection = new PDO($dsn, $user, $password, $options); } catch (PDOException $e) {
echo 'Fallo conexión: '. $e->getMessage();
}
$sql = "SELECT ....WHERE artist.artist_id = $i"; //This is to call only artist that the user actually have access to see.
$query = $connection->prepare($sql);
$query->execute();
while($row = $query->fetch()){
$artists[] = $row;
};
if (isset($artists)){
// 1- This is the First loop, it looks for the artist. This is working, barely.
foreach($artists as $art) {
$a = $art['artist_id']
$data['info'] .= "<div class='Main'>
<div class='MainResult'>
{$art['artist_name']}
</div>
<div>
<div class='VisitedPlaces'>
<?php
$sql='SELECT country_name, country_city, country_time FROM country JOIN ...... WHERE... = $a';
$query = $connection->prepare($sql);
$query->execute();
// 2- Here's the second loop, that look for the countries related to the artist. The idea is that once it finish, look for the next artist in the first loop. This one don't works.
while($row = $query->fetch()){
$country = $row['country_name'];
$city = $row['country_city'];
$time = $row['country_time'];
echo '<div class="rslt">
<h2>'.$country.'</h2>
<span>'.$city.'</span>
<span>'.$time.'</span>
</div>';
};
?>
</div>
</div>";
}
echo JSON_encode($data);
}
It's not actually an answer, but some of my suggestions/advices.
First of all code logic is partially not understandable, some variables appears from nowhere. For example: $i and $artists.
Next one - why do you need to return an html-code instead of pure-data?
Third, subjective on me I guess, that the access to the mysql every time is a bad idea.
My vision looks like that:
notice: I haven't test this
<?php
$data = array();
$data['info'] = array(); // changes
$rol = $_POST['id'];
if (isset($_POST['id'])){
$dsn = 'mysql:dbname=ec;host=localhost;port=3306';
$user = 'root';
$password = '';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$connection = new PDO($dsn, $user, $password, $options); } catch (PDOException $e) {
echo 'Fallo conexión: '. $e->getMessage();
die(); // added
}
// what data gets from database?.. idk
// it seems like companies .. what / why / where it used in this code ? unknown
// what is $i ? I guess - artist_id
$sql = "SELECT ....WHERE artist.artist_id = :artist_id";
$query = $connection->prepare($sql);
$query->bindParam(':artist_id', $i, \PDO::PARAM_INT); // suggestion
$query->execute();
$companies = $query->fetchAll(\PDO::FETCH_ASSOC);
// from where we have got this ?
if (isset($countries)){
// 1- This is the First loop, it looks for the artist. This is working, barely.
$artist_ids = array();
// from where this too ? okay, just use it
foreach($artists as $art) {
$artist = array();
// it's just a suggestion about your table scheme
$artist_id = $art['artist_id'];
$artist_ids[] = $artist_id;
$artist['name'] = $art['artist_name'];
$artist['visited_places'] = array();
$data['info'][$artist_id] = $artist;
}
// here is not an actual sql-query, I suggest that country data and artists data are separated
// and sql must be modified to get data from both table at once
$sql = 'select country_name, country_city, country_time, artist_id from country join ... where ... and artist_id in ('.implode(',',$artist_ids).')';
$query = $connection->prepare($sql);
$query->execute();
// I don't know how many rows it will be
// make this safer, get row by row
while ($row = $query->fetch(\PDO::FETCH_ASSOC)) {
$artist_id = $row['artist_id']; // according the new query
$place = array();
$place['country'] = $row['country_name'];
$place['city'] = $row['country_city'];
$place['time'] = $row['country_time'];
$data['info'][$artist_id]['visited_places'][] = $place;
}
} // if $countries
// send back pure-data, your javascript can do anything
echo JSON_encode($data);
} // if $_POST['id']
after all your front-end javascript application will receive a JSON-string, something like this: {"info":{"110":{"name":"Michael Jackson","visited_places":[{"country_name":"JP","country_city":"Tokyo","country_time":"12-sep-1987"},{"country_name":"US","country_city":"New-York","country_time":"03-mar-1988"},{"country_name":"IT","country_city":"Rome","country_time":"23-may-1988"}]}}}
php source:
[info] => Array
(
[110] => Array
(
[name] => Michael Jackson
[visited_places] => Array
(
[0] => Array
(
[country_name] => JP
[country_city] => Tokyo
[country_time] => 12-sep-1987
)
[1] => Array
(
[country_name] => US
[country_city] => New-York
[country_time] => 03-mar-1988
)
[2] => Array
(
[country_name] => IT
[country_city] => Rome
[country_time] => 23-may-1988
)
)
)
)
)

Change Div Class with Javascript if DateTime variable is passed

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

Categories

Resources