Recently, ive started tyring out arshaw's fullcalendar. Along the developing journey, i was searching through websites on solution to get the event color to change based on the dates of the event and the current date. This code is written with HTML and PHP with Javascript.
This is an answer to my own questions posts based on what i achieve as there is no similar questions with solutions to this.
So below is my answer and how the FullCalendar looks like.
To clarify, i am using odbc with microsoft Access as database.
My way of doing this is as below:
Events at fullcalendar script
events: [
<?php
include 'connect.php'; //connect to database
function getColor($date) {
$currentDate = date('Y-m-d');
$oneweekDate = date('Y-m-d',strtotime('-1 week')); // this part is to compare with the date 1 week ago
$eventColor = '';
if ($date == $currentDate) {
$eventColor = '#fb8c00';
} else if($date > $oneweekDate && $date < $currentDate){
$eventColor = '#ff0000';
} else if($date < $oneweekDate){
$eventColor = '#696969';
} else {
$eventColor = '#008000';
}
return $eventColor;
}
$sql="SELECT * FROM masterlist1";
$result=odbc_exec($conn,$sql);
while($row=odbc_fetch_array($result)){
$newEnd = date("Y-m-d", strtotime($row['Calibration_Due_Date']));
$color = getColor($newEnd); //store the date from database into a PHP variable and then call the PHP function getColor to get return result
?>
{
title: '--title--', <!--u may get info from fullcalendar.io on the documentations for these parts-->
start: '--start date--',
end: '--end date--',
description : '--description--',
color : '<?php echo $color?>' <!-- this part is where we get the return result from the getColor function and store it into $color variable and then echo it out here for the event color.-->
},
<?php } ?>
],
Related
How can I pick a single date from my date range picker?
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#from_date").datepicker();
$("#to_date").datepicker();
});
$('#filter').click(function(){
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
if(from_date != '' && to_date != '')
{
$.ajax({
url:"filtertable.php",
method:"POST",
data:{from_date:from_date, to_date:to_date},
success:function(data)
{
$('#order_table').html(data);
}
});
}
else
{
alert("Please Select Date");
}
});
});
</script>
here's my query coming from the date range picker:
query = "SELECT *
FROM gsm2 WHERE setTime BETWEEN '".$_POST["from_date"]."' AND
'".$_POST["to_date"]."'
If u I try to select 2 same dates it doesn't work because of this
$query = "SELECT *
FROM gsm2 WHERE setTime BETWEEN '".$_POST["from_date"]."' AND
'".$_POST["to_date"]."' ";
I need to add a statement which is
`$query ="SELECT *
FROM gsm2 WHERE setTime = '".$_POST["from_date"]."' OR
'".$_POST["to_date"]."' ";
how can I add this condition to the old query?
Instead of between you can just do the manual:
SELECT *
FROM gsm2
WHERE setTime >= :fromTime AND setTime <= :toTime
Notice how I'm using placeholders there? You should too, and also use prepared statements.
In practice if you are using MySQLi you could do:
$db = mysqli_connect(...); //Your connection
$stmt = $db->prepare("SELECT * FROM gsm2 WHERE setTime >= ? AND setTime <= ?");
$from = filter_input(INPUT_POST, "from_date");
$to = filter_input(INPUT_POST, "to_date");
$stmt->bind_param("ss", $from, $to);
$stmt->execute();
$res = $stmt->get_result();
// Do things like $res->fetch_assoc or similar here
Note that if your $_POST data are dates but your SQL fields are DATETIME then you might need to do some sort of casting e.g. do WHERE DATE(setTime) >= ? AND DATE(setTime) <= ?
I may be wrong (as I'm not equipped to test it right now), but this should work:
$query = "SELECT *
FROM gsm2 WHERE setTime BETWEEN ".$_POST['from_date']." AND ".$_POST['to_date'].";
Going by the assumption that your initial query was right, but your PHP code was throwing up some errors as you are using loads of (' and ")'s.
Mainly posting to point out that you are accepting user input and throwing it straight into a SQL query. I am honestly surprised that in 2018 on StackOverflow, so many users in this category are placing PHP input variables directly into a SQL query and then executing it without checking the input to ensure that it is valid first.
Input such as 1; DROP TABLE gsm2; could have the potential to delete your entire table. I'm not sure what kind of server-side firewalls are in place to deal with this type of attack, but it's terrible practice all the same.
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 really new at back-end stuff and I'm building a Facebook app with multiple photo entries with voting mechanics. You can vote one or multiple entries once per day and it also detects your Facebook ID so that when you vote, the database detects your Facebook ID, the entry number you voted, and the date you voted. When you vote during the current date, a pop-up will appear that says "you successfully voted". Then when you try again the same date, the pop-up's message will change and instead, it will say "try to vote again tomorrow". It also shows the number of votes on the entry page.
My only problem is that when you're a first time user, it works fine, you can vote all the entries on the current date, but then when you come back the next day, when you vote, the pop-up will still say that you already voted, and the vote count will not update.
Here's the code for the PHP page: (edited this, already solved the problem, thanks for the help)
date_default_timezone_set('Asia/Manila');
// Get last vote date: fetch_date_voted returns none if user voted for first time
$current_date = date('Y-m-d');
$fetch_date_return = $this->fetch_date_voted($entry_id, $facebook_id, $table_prefix, $conn);
$last_vote_date = $fetch_date_return['last_date'];
$return['date_last_voted'] = $fetch_date_return;
// Below is a code i got from stackoverflow - 844641242329946 (kristina id)
/*if( $last_vote_date && ($last_vote_date == "none" || (strtotime($last_vote_date) + (60*60*24)) < strtotime($current_date))){*/
// Below is the original code
if( $last_vote_date == "none" || $last_vote_date < $current_date ) {
$table_name = $table_prefix . '_voter';
$query = $conn->query("
INSERT INTO $table_name
(facebook_id, entry_id, date_voted)
VALUES
($facebook_id, $entry_id, '$current_date')
");
//
// After doing INSERT, the variable $query will return a TRUE status
if ( $query ) {
// If the date fetched is TRUE, it will UPDATE
$update = $this->update_count($entry_id, $table_prefix, $conn);
// If update is successful, it will fetch the latest vote_count
if($update) {
$fetched_data = $this->fetch_current_count($entry_id, $table_prefix, $conn);
if ($fetched_data['status']) {
$return['status'] = true;
$return['vote_count'] = $fetched_data['vote_count'];
} else {
$return['status'] = false;
}
} else {
$return['status'] = false;
}
} else {
die('Error : ('. $conn->errno .') '. $conn->error);
$return['status'] = false;
$return['error_response'] = $conn->error;
}
} else {
$return['status'] = false;
$return['error_response'] = 'date_invalid';
}
echo json_encode($return);
//$query->close();
$conn->close();
}
$last_vote_date AND $current_date are string representations of a date, convert them to time and it works:
strotime($last_vote_date) < strotime($current_date)
Beware that this will always return true, because you want them to not use it for a day, so it would be:
if( $last_vote_date && ($last_vote_date == "none" || (strtotime($last_vote_date) + (60*60*24)) < strtotime($current_date))){
to add 24 hours.
Not sure if this is possible but here goes, I have a basic PDO query that stores the results in a array.
<?php
// configuration
$dbtype = "";
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$title = 'PHP AJAX';
// query
$sql = "SELECT * FROM thankyou";
$q = $conn->prepare($sql);
$q->execute(array($title));
$q->setFetchMode(PDO::FETCH_BOTH);
// fetch
while($r = $q->fetch()){
echo"<br>";
print_r ($r);
}
?>
Now the bit I can't get my head around, I have also never used JavaScript. Can I rotate through the results to show one at a time for 5-10 seconds then show another? It can be random or in order, I'm not fussed. I found this, which works, but can't figure out how to get the array into it. I am aware one is client side and one is server side.
<script type="text/javascript">
var rotatingTextElement;
var rotatingText = new Array();
var ctr = 0;
function initRotateText() {
rotatingTextElement = document.getElementById("textToChange");
rotatingText[0] = rotatingTextElement.innerHTML; // store the content that's already on the page
rotatingText[1] = "need to write PDO array here";
setInterval(rotateText, 5000);
}
function rotateText() {
ctr++;
if(ctr >= rotatingText.length) {
ctr = 0;
}
rotatingTextElement.innerHTML = rotatingText[ctr];
}
window.onload = initRotateText;
</script>
and this is were the results are shown
<span id="textToChange">this is were the result is displayed</span>
If I need to do it a totally different way, it's not a problem if someone can point me in the correct direction.
If you're not so familiar with JavaScript, I also suggest using some JS library for the task. In fact, Prototype.js has a class exactly for this purpose: http://prototypejs.org/doc/latest/ajax/Ajax/PeriodicalUpdater/index.html
A working example: http://www.tutorialspoint.com/prototype/prototype_ajax_periodicalupdater.htm
i decided to use AJAX to call a seprate PHP page in the end and works fine this is the updated page.
<script type="text/javascript">
$(function() {
getStatus();
});
function getStatus() {
$('div#status').load('thankyou.php')//Thankyou being the page the query is on
setTimeout("getStatus()",5000);//refreshes every 5 seconds
}
</script>
The query itself is a standard PDO
$query = $db->query("SELECT * FROM `thankyou` ORDER BY RAND() LIMIT 1
Thanks for the pointers all.
I have a main select list of courses which drives various things on a page. When a course is selected another select list will be repopulated with the start date of that course up to 6 months in advance. Also, I have a table on the page with the students name and phone number, when a course is selected, the table will be repopulated with all the students enrolled onto that course. My problem is I will be getting various different things from PHP via JSON i.e. the students and the starting date. How can I therefore pass more than one thing to jQuery? What if the course select list affected not just 2 things but 3, 5 or even 10? How would we handle that with PHP and jQuery?
foreach($m as $meta)
{
$metaCourse = $this->getCourseInfo($meta['parent_course']);
//populate the select list with the name of each course
$metaSelectList .= '<option id="select'.$count.'" value="'.$metaCourse['id'].'">'.$metaCourse['fullname'].'</option>';
$count++;
//get only the first course's dates
if($count3 == 1)
{
$startDate = intval( $course->getStartDate(50) );
$endDate = strtotime('+6 month', $startDate);
//populates the select list with the starting date of the course up to the next six months
for($date = $startDate; $date <= $endDate ; $date = strtotime('+1 day', $date))
{
$dateSelectList .= '<option id="select'.$count2.'" value="'.$date.'">'.date('D d F Y', $date).'</option>';
$count2++;
}
$count3++;
$students = $s->getStudents($metaCourse['id']);
$content = $this->createStudentTable($students);
}
}
This is my handler for the AJAX...FOR NOW (I haven't implemented the students table yet as I'm still trying to figure out how to pass multiple pieces of data to jQuery). Basically each time a course is selected, PHP creates a new select list with the appropriate dates and then passes it to jQuery. I'm not sure if I should do this in JavaScript or in PHP.
if (isset($_GET['pid']) && (isset($_GET['ajax']) && $_GET['ajax'] == "true"))//this is for lesson select list
{
$pid = intval( $_GET['pid'] );
$c = new CourseCreator();
$startDate = intval( $c->getStartDate($pid) );
$endDate = strtotime('+6 month', $startDate);
$dateSelectList = '<select name="dateSelect" id="dateSelect">';
//populates the select list with the starting date of the course up to the next six months
for($date = $startDate; $date <= $endDate ; $date = strtotime('+1 day', $date))
{
$dateSelectList .= '<option id="select'.$count2.'" value="'.$date.'">'.date('D d F Y', $date).'</option>';
$count2++;
}
$dateSelectList .= '</select>';
echo json_encode($dateSelectList);
exit;
}
My jQuery handler:
$('#metaSelect').live('change', function()
{
$.getJSON('?ajax=true&pid='+$('#metaSelect').val(), function(data)
{
alert(data);
$('#dateSelectDiv').html(data);
});
});
You can easily pass ALOT of data from PHP to your HTML via JSON (which you seem to of put in basic already)
However to expand on what you have - heres a quick example
<?php
$arrayOfStuff = array("theKey" => "theEntry", 123 => "Bob Dow", 56 => "Charlie Bronw", 20 => 'Monkey!', "theMyID" => $_POST['myID']);
echo json_encode($arrayOfStuff);
?>
On your HTML side.
<script>
$.post("/theurl/", {type: "fetchArrayOfStuff", myID: 24}, function(success) {
//your success object will look like this
/*
{
theKey: 'theEntry',
123: 'Bob Dow',
56: 'Charlie Bronw',
20: 'Monkey!',
theMyID: 24
}
so you can easily access any of the data.
alert(success.theKey);
alert(success[123]);
alert(success[56]);
alert(success[20]);
alert(success.theMyID);
*/
//we can iterate through the success JSON!
for(var x in success) {
alert(x + "::" + success[x]);
};
}, "json");
</script>
In the long run - your MUCH better of letting the backend do the backend stuff, and the front end doing the front-end stuff.
What this means is, try keep the HTML generation as far away as possible from the back-end, so instead of constantly passing
for($date = $startDate; $date <= $endDate ; $date = strtotime('+1 day', $date))
{
$dateSelectList .= '<option id="select'.$count2.'" value="'.$date.'">'.date('D d F Y', $date).'</option>';
$count2++;
}
You could perhaps
$date = $startDate;
$myJson = array()
while($date <= $endDate) {
$myJson[] = array("date" => $date, "formattedDate" => date('D d F Y', $date));
$date += 86400; //86400 is the value of 1 day.
}
echo json_encode($myJson);
And you can just do a simple iteration on your HTML code.
<script>
$.get("/", {ajax: true, pid: $('#metaSelect').val()}, function(success) {
//we can iterate through the success JSON!
var _dom = $('#dateSelectDiv').html(''); //just to clear it out.
for(var x in success) {
_dom.append("<option value='"+success[x].date+"'>"+success[x].formattedDate+"</option>");
};
}, "json");
</script>
So as you can see - you can pass alot of data using JSON
Maybe look at some of the documentation to - http://api.jquery.com/jQuery.get/ , http://api.jquery.com/jQuery.post/ - might give you more ideas.
Best of luck to you