How to get different data based on date selected from datepicker? - php

I have an excel sheet which link is given below.
In this sheet I gave 3 sections of cse.
I want to display them in php and when i select the date from date picker and section from drop down that section presented and absentees should be display. I don't know how to do this.
$students = [
['CSE-A' => 'PRESENT'],
['CSE-A' => 'PRESENT'],
['CSE-B' => 'ABSENT'],
['CSE-B' => 'ABSENT'],
['CSE-A' => 'ABSENT'],
['CSE-B' => 'PRESENT'],
['CSE-B' => 'ABSENT'],
['CSE-A' => 'ABSENT'],
['CSE-C' => 'ABSENT'],
['CSE-C' => 'PRESENT']
];
$outputs = [];
foreach($students as $array) {
foreach($array as $key => $value) {
if (!isset($outputs[$key])) {
$outputs[$key] = [
'present' => 0,
'absent' => 0,
];
}
//check value
if ($array[$key] === 'PRESENT') {
$outputs[$key]['present']++;
} else if ($array[$key] === 'ABSENT') {
$outputs[$key]['absent']++;
}
}
}
foreach($outputs as $key => $value) {
echo $key.
"\n";
echo "Present Totals: ".$value['present'].
"\n";
echo "absent Totals: ".$value['absent'].
"\n";
echo "--------------\n";
}
I tried up to this. But I am confusing when date from datepicker and section from dropdown selected how to display that date students presences and absences on selected option.

Ok. The code you need is below. I tested it and it works.
Explanation: It crates a div for every match of dates and cse that exists in the table, which includes the nuber of presentiew and the number of absenties. Then, using javascript, when a selection is choosed, it checks if both the date and the cse selection is chosen. If yes, it makes the div with the selected date and cse visible. If there isn't the corresponding div (because the array doesn't have a student for that cse in that day) an appropriate message is show. Otherwise the data for the selected date and cse are shown.
What it does is also included in the comments. If you have any question or you wanted something different please let me know.
<html>
<?php
$students = array
(
array('CSE-A','PRESENT',"2-10-2017"),
array('CSE-A','PRESENT',"2-10-2017"),
array('CSE-B','ABSENT',"3-10-2017"),
array('CSE-B','ABSENT',"3-10-2017"),
array('CSE-A','ABSENT',"3-10-2017"),
array('CSE-B','PRESENT',"4-10-2017"),
array('CSE-B','ABSENT',"4-10-2017"),
array('CSE-A','ABSENT',"5-10-2017"),
array('CSE-C','ABSENT',"5-10-2017"),
array('CSE-C','PRESENT',"5-10-2017")
);
$outputs = [];
foreach($students as $array) {
$cse = $array[0];
$present = $array[1];
$date = $array[2];
$entry = $cse.", ".$date;
if (!isset($outputs[$entry])) {
$outputs[$entry] = [
'present' => 0,
'absent' => 0,
];
}
//check value
if ($present === 'PRESENT') {
$outputs[$entry]['present']++;
} else if ($present === 'ABSENT') {
$outputs[$entry]['absent']++;
}
}
// Save all availbale cse, for the dropdown choices
$all_cse = array();
foreach($students as $array) {
$cse = $array[0];
array_push($all_cse,$cse);
}
$all_cse = array_combine($all_cse, $all_cse);
// Save all availbale dates, for the dropdown choices
$all_dates = array();
foreach($students as $array) {
$date = $array[2];
array_push($all_dates,$date);
}
$all_dates = array_combine($all_dates, $all_dates);
?>
<body>
<select id="cse" onchange="myFunction()">
<option disabled selected value> -- select an option -- </option>
<?php
foreach($all_cse as $cse) {
echo "<option value='".$cse."'>".$cse."</option>";
}
?>
</select>
<select id="dates" onchange="myFunction()">
<option disabled selected value> -- select an option -- </option>
<?php
foreach($all_dates as $date) {
echo "<option value='".$date."'>".$date."</option>";
}
?>
</select>
<br><br>
<div id="data">
</div>
<?php
foreach($outputs as $key => $value) {
// Create a div for every match of cse and date that exists.
echo "<div id='".$key."' style='display:none;'>";
"<br>";
echo "Present Totals: ".$value['present'].
"<br>";
echo "absent Totals: ".$value['absent'].
"<br>";
echo "</div>";
}
?>
</body>
</html>
<script type="text/javascript">
var lastDiv;
function myFunction() {
var date = document.getElementById("dates").value;
var cse = document.getElementById("cse").value;
if (cse!="" && date!=""){
// Make invisible the div for the previous choice
if (lastDiv!=null){
lastDiv.style.display = "none";
}
lastDiv = document.getElementById(cse + ", " + date);
// Make visible the div for the current choice
if (lastDiv!=null){
document.getElementById("data").innerHTML = cse +"<br>Date: " + date;
lastDiv.style.display = "block";
} else {
document.getElementById("data").innerHTML = "No matches found for this cse in this date.";
}
}
}
</script>

Related

Merge 2 arrays after 1 was in a loop

I have a form with a drop down. It looks at previous weeks results for an array of teams used. If the team was used it disables the selection on the drop down:
This is the working code:
echo '<select name="survpick" id="survpick">';
$thisweek = (int)getCurrentWeek()-1;
for ($pi=1; $pi<$week; $pi++) {
if ($surv_pick_options_h[$j] == $survpicks[$pi]) {
$noshowhome = true;
}
if ($surv_pick_options_v[$j] == $survpicks[$pi]) {
$noshowvisitor = true;
}
}
if ($noshowhome) {
echo '<option value="" style="background-color:pink" disabled>'.$surv_pick_options_h[$j].'</option>';
} else {
if ($currentID == $surv_pick_options_h[$j]) {
echo '<option value="'.$surv_pick_options_h[$j].'" selected>'.$surv_pick_options_h[$j].'</option>';
} else {
echo '<option value="'.$surv_pick_options_h[$j].'" >'.$surv_pick_options_h[$j].'</option>';
}
}
if ($noshowvisitor) {
echo '<option value="" style="background-color:pink" disabled> '.$surv_pick_options_v[$j].'</option>';
}
else {
if ($currentID == $surv_pick_options_v[$j]) {
echo '<option value="'.$surv_pick_options_v[$j].'" selected>'.$surv_pick_options_v[$j].'</option>';
}
else {
echo '<option value="'.$surv_pick_options_v[$j].'" >'.$surv_pick_options_v[$j].'</option>';
}
}
echo '</select>';
I have 2 more arrays, one for current week home teams that have expired and one for current week visitor teams that expired. Somehow I need to account for those current week expired teams in the calculation. Since the for loop is only looking at previous weeks, i could not find a way to merge. I tried inside the loop and outside the loop. Is this even possible?
Array ( $survpicks)
[1] => DET
[2] => TB
[3] => NE
[5] => JAX
[4] => PHI
[6] => IND
Array ( $surv_pick_expired_h)
[0] => KC
Array ($surv_pick_expired_v)
[0] => OAK
There is also a chance that one of the $survpicks could also be in one of the $surv_pick_expired_h or $surv_pick_expired_v arrays. Right now the drop down shows the values from $survpicks as disabled. I need to be able to also include the values from $surv_pick_expired_h and $surv_pick_expired_v arrays as disabled
I don't fully understand your question, but may the array_merge() and in_array() functions help?
$toDisable = array_merge($survpicks, $surv_pick_expired_h, $surv_pick_expired_v);
foreach($all as $something) {
if(in_array($something, $toDisable)) {
// disable
} else {
// enable
}
}
I hope this helps somewhat:
// this will contain all the survpicks up to last week,
// so now this week is not disabled
$survpicks_to_disable = array_slice($survpicks,0,$week-1);
// all the expired teams are to be disabled
$disabled = array_merge($survpicks_to_disable,$surv_pick_expired_h,$surv_pick_expired_v);
echo '<select name="survpick" id="survpick">
<option default>Make Selection</option>';
foreach($surv_pick_options_h as $home){
echo '<option value="'.$home.'"'.(in_array($home,$disabled)?' style="background-color:pink" disabled':'').($home == $currentID?' selected':'').'>'.$home.'</option>';
}
foreach($surv_pick_options_v as $visitor){
echo '<option value="'.$visitor.'"'.(in_array($visitor,$disabled)?' style="background-color:pink" disabled':'').($visitor == $currentID?' selected':'').'>'.$visitor.'</option>';
}
echo '</select>';
Why not put this into your style, so you don't need the inline styles:
#survpick option[disabled] {
background-color: pink;
}

How to get the value which user has selected in php?

I have a little problem here. I have a list, which is:
<form action="display.php" method="post">
<select name="holiday">
<option value="month">Kiekvieno mėnesio skaičiavimas</option>
<option value="day">Kiekvienos dienos skaičiavimas</option>
</select>
<br> <br>
<input type="submit" name="select" value="Pasirinkti" />
</form>
What I need to do is that when the user selects value ="month", php code would do one action, and when the user selects value ="day", php code would do another action?
My php code looks like this:
<?php
if($_POST['select']){
// Storing selected value in a variable
$selectedValue= $_POST['holiday'];
}
else if ($selectedValue == $_POST['month']) {
$todaysDate = new DateTime();
while ($employee = $select->fetch()){
$employmentDateValue = new DateTime($employee['employment_date']);
// Comparing employment date with today's date
$differenceBetweenDates = date_diff($employmentDateValue, $todaysDate);
$workMonths = $differenceBetweenDates->y * 12 + $differenceBetweenDates->m;
$holidayDays = $workMonths *4;
echo "<tr>";
echo "<td>".$employee['name']."</td>";
echo "<td>".$employee['surname']."</td>";
echo "<td>".$employee['employment_date']."</td>";
echo "<td>".$workMonths."</td>";
echo "<td>".$holidayDays."</td>";
echo "</tr>";
}
}
else {
echo "Lalalala";
}
?>
I've tried to do so with $_POST['select'], but it doesn't work. Thanks for any help guys
<?php
if($_POST['select']){
// Storing selected value in a variable
$selectedValue= $_POST['holiday'];
if ($selectedValue == 'month') {
}
else if ($selectedValue == 'day') {
}
else{
echo "Lalalala";
}
}
?>
You need to do $_POST['holiday'], so change:
if($_POST['select']){
// Storing selected value in a variable
$selectedValue= $_POST['holiday'];
}
to
if($_POST['holiday']){
// Storing selected value in a variable
$selectedValue = $_POST['holiday'];
}
You also need to change the line:
else if ($selectedValue == $_POST['month']) {
So it's not part of the original if statement:
if ($selectedValue == 'month') {
// your code
}
else {
echo "Lalalala";
}

multiple attribute form output

i have had made a number of changes to the below program but am really stumped on my last task- i need a multiple attribute to pull multiple 'teams' data (points,goal difference etc) with php form. i can get single teams to work but not multiple. see screen attached and heres my code below.
![enter image description here][1]
<html>
<head>
<style>
.red {color: red}
</style>
<title>Table</title>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" ){
$tablesPage = "http://www.bbc.com/sport/football/tables";
if(!empty($_POST["team"])){
$teamData= getTeamData($_POST["team"] , $tablesPage); //get associative array of team data
if(!empty($_POST["data"]) && $_POST["data"] == "results"){
echo getResults($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "position"){
echo getPosition($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "two points for a win"){
echo getPoints($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "goal difference"){
echo getDifference($teamData);
}
}
}
function getPosition($teamData){
/*This function takes an array of team data and returns a string containing the name of the team and its position in the leauge */
return "Team ". $teamData["team"] ." are currently number " . $teamData["position"] . " in the league " ;
}
function getResults($teamData){
/*This function takes an array of team data and returns a string containing the results of the team */
return $teamData["team"] ." have won " . $teamData["won"] . " , drawn " . $teamData["drew"] . " , and lost " . $teamData["lost"] . " games to date " ;
}
function getPoints($teamData){
/*This function takes an array of team data and returns a string containing the points and calculates the old two points system */
$oldpoints = $teamData["won"] * 2 + $teamData["drew"];
return $teamData["team"] ." have " . $teamData["points"] . " points under the current system " . "<br> Under two points for a win they would have " . $oldpoints ;
}
function getDifference($teamData){
/*This function takes an array of team data and returns a string containing the name of the team and its goal difference in the leauge */
return $teamData["team"] ." goal difference is " . $teamData["difference"] . " at the moment " ;
}
function getTeamData($team, $tablesPage){
/* This function takes a webpage url and the name of a team as two string arguments. e.g. getTeam(""http://www.bbc.com/sport/football/tables", "liverpool")
It returns an array of data about the team.
You don't need to understand what this function does just that it returns an array which contains keya and values. The values map to the following keys:
"position", "team", "played", "won", "drew", "lost", "for", "against", "difference", "points"
*/
$html = new DOMDocument();
#$html->loadHtmlFile($tablesPage); //use DOM
#$xpath = new DOMXPath($html); //use XPath
$items = $xpath->query('//td/a[text()="' . $team . '"]/../..'); //get the relevant table row
$values[] = array();
foreach($items as $node){
foreach($node->childNodes as $child) {
if($child->nodeType == 1) array_push($values, $child->nodeValue); //KLUDGE
}
}
$values[2] = substr($values[2], -1); //KLUDGE
$values = array_slice( $values, 2, count($values)-4); //KLUDGE
$keys = array("position", "team", "played", "won", "drew", "lost", "for", "against", "difference", "points");
return array_combine($keys, $values);
}
?>
<br>
Select a team and a data item about that team
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<select name="team[]" multiple="multiple" size="3">
<option value=""></option>
<option value="Everton">Everton</option>
<option value="Arsenal">Arsenal</option>
<option value="Chelsea">Chelsea</option>
<option value="Man Utd">Man Utd</option>
<option value="Liverpool">Liverpool</option>
</select>
<select name="data">
<option value="position">position</option>
<option value="results">results</option>
<option value="two points for a win">two points for a win</option>
<option value="goal difference">goal difference</option>
<select>
<input type="submit" value="Get Data"></input>
</select>
</form>
</body>
</html>
Here is the code that you need to replace. I have left the 'debug' code in so you can see what is happening. just delete it when you are done.
Removed debug code.
Tested code: PHP 5.3.18 on windows xp.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" ){
$tablesPage = "http://www.bbc.com/sport/football/tables";
if(!empty($_POST["team"])){
// remember that the $_POST['team'] is an array of team names
foreach($_POST['team'] as $currentTeam) {
$teamData= getTeamData($currentTeam , $tablesPage); //get associative array of team data
if(!empty($_POST["data"]) && $_POST["data"] == "results"){
echo getResults($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "position"){
echo getPosition($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "two points for a win"){
echo getPoints($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "goal difference"){
echo getDifference($teamData);
}
echo '<br />';
} // end currentTeam
}
}

How to Set a Dropdowns Default Selection Based on the Logged in User

I have a dropdown control which and I would like it to default to a specific option based on the access of the logged in user. For example, the dropdown has 10 options but only administrators have access to view all 10 options. The majority of users only have access to 1 of the options though. The page contents are hidden/displayed based on whether or not the value of the dropdown is null.
Question: Using the example above, if an admin is logged in I need the dropdown to default to "Select an option". This way the page content is hidden. On the other hand, if a user with access to only 1 is logged in, I need it to default to that 1. This way they don't have to select anything and, by default the page content is displayed. How do I go about doing this?
Below is my current code which handles what the dropdown displays based on when a selection is made.
PHP/HTML
// Hide/Show main content div
<?php
if (isset($_GET['src'])) {
$src = $_GET['src'];
} else {
?>
<style>
#divmain { display: none; }
</style>
}
<?php } ?>
// Start of form, header, etc.
<select name="select1" id="select1">
<?php
$sql = getOptions();
$data = makeConnection($sql);
if ($src == null) { // If value is null, default to 'Select an option'
echo "<option selected value=\"\" disabled=\"disabled\">--Select an option--</option>";
while ($row = odbc_fetch_array($db)) {
echo "<option value=\"".$row['content']."\">".$row['content']."</option>";
}
} else { // If value not null keep the selected value selected
while ($row = odbc_fetch_array($db)) {
if ($row['content'] == $src) { $selected = " selected "; }
else { $selected = " "; }
echo "<option value=\"".$row['content']."\" ".$selected.">".$row['content']."</option>";
}
}
?>
</select>
JS
// Pass selected value on change
$('#select1').change(function() {
var sel = $(this).val();
location.href = "page1.php?src=" + sel;
}
SQL
// Hardcoding user for testing purposes, THIS WILL BE CHANGED
function getOptions() {
$results = "SELECT content, userid FROM table WHERE userid = 'username'";
return $results;
}
Any help is much appreciated and please let me know if I'm not clear about anything.
Got some help and have it figured out now. Here is the revised code:
PHP/HTML
// Hide/Show main content div
<?php
$src = null;
if (isset($_GET['src'])) {
$src = $_GET['src'];
} else {
?>
<style>
#divmain { display: none; }
</style>
}
<?php } ?>
// Start of form, header, etc.
<select name="select1" id="select1">
<?php
$sql = getOptions();
$data = makeConnection($sql);
if ($src == null) {
$i = 0;
$content = "";
while ($row = odbc_fetch_array($db)) {
$content .= "<option value=\"".$row['content']."\">".$row['content']."</option>";
$i++;
}
if ($i > 1) {
echo "<option selected value=\"\" disabled=\"disabled\">--Select an option--</option>";
}
echo $content;
if ($i > 1) { $oneopt = 1; }
else { $oneopt = 0; }
} else {
while ($row = odbc_fetch_array($db)) {
if ($row['content'] == $src) { $selected = " selected "; }
else { $selected = " "; }
echo "<option value=\"".$row['content']."\" ".$selected.">".$row['content']."</option>";
}
}
?>
</select>
JS
$('#select1').change(function() {
var sel = $(this).val();
location.href = "page1.php?src=" + sel;
}
<?php
global $optone;
if ($optone == 1) {
echo "$('#select1').trigger('change');";
}
?>
SQL -- Stays the same
#chenasraf really appreciate the help! Hope this can be of some help to someone in the future!
The preselected option is always the first to have a "selected" attribute. Your first disabled one has it first on all cases, so it's always chosen. Remove that and work from there.
On a side note, I think you can manage to make this options part work better. I've taken the liberty of rewriting it for you:
<select name="select1" id="select1">
<?php
$selected = '';
while ($row = obdc_fetch_array($db)) {
$options[] = '<option value="'.$row['content'].'">'.$row['content'].'</option>';
if ($row['content'] == $src)
$selected = count($options) - 1;
}
array_unshift($options, '<option disabled="disabled"', $selected == '' ? ' selected="selected"' : '','>--Select an option--</option>');
foreach ($options as $option) {
echo $option;
}
?>
</select>

How to keep selected value in a dropdown box using JQUERY?

Hi am using a jquery code like this
$(".selfont").change(function(event){
$('#dav').val();
window.location ='?davQ=' + $('#dav').val() + '&pathogenQ=' + $('#pathogen').val() + '&topicQ=' + $('#topicF').val() ;
});
I want to keep the dropdown value selected by the user in each dropdown boxes. But at present the value is not the one selected by the user, its always showing the first value. How can I set the dropdown field with value selected by the user using jquery? Please help me.
My first select box code is like below
<select name="dav" id="dav" style="width: 275px" class='selfont' >
<option value='' class=''>Select one</option>
<?php
$test = mysql_query("SELECT DISTINCT DataVersion FROM olivesdeptable ORDER BY DataVersion DESC");
$i=1;
while($numval=mysql_fetch_array($test))
{
print "<option value=\"".$numval['DataVersion']."\">".$numval['DataVersion']."</option>";
$i=$i+1;
}
?>
</select>
Even if we select value it will show as "Select one" in the field.
javascript code for dropdown fields
<script type="text/javascript">
if (document.getElementById("dav").selectedIndex < 1)
{
document.getElementById('pathogen').selectedIndex = "";
document.getElementById('pathogen').disabled = true;
}
if (document.getElementById("pathogen").selectedIndex < 1)
{
document.getElementById('topicF').selectedIndex = "";
document.getElementById('topicF').disabled = true;
}
if (document.getElementById("topicF").selectedIndex < 1)
{
document.getElementById('ind').selectedIndex = "";
document.getElementById('ind').disabled = true;
}
if (document.getElementById("ind").selectedIndex < 1)
{
document.getElementById('subind').selectedIndex = "";
document.getElementById('subind').disabled = true;
}
if (document.getElementById("subind").selectedIndex < 1)
{
document.getElementById('countryR').selectedIndex = "";
document.getElementById('countryRF').options.length = 0;
document.getElementById('countryRF').selectedIndex = "";
document.getElementById('countryR').disabled = true;
document.getElementById('countryRF').disabled = true;
}
</script>
even the value is updated, the second drop down box is showing as disabled ?
Next dropdown field markup is as below
<select name="pathogen" id="pathogen" style="width: 275px" class='selfont' >
<option value=''>Select one</option>
<?php
$test = mysql_query("SELECT DISTINCT Pathogen FROM olivesdeptable where DataVersion='$davQ' ORDER BY Pathogen ASC");
$i=1;
while($numval=mysql_fetch_array($test))
{
print "<option value=\"".$numval['Pathogen']."\">".$numval['Pathogen']."</option>";
$i=$i+1;
}
?>
</select>
only first dropbox value is working for next dropbox value is storing in url but in page the value shows as 'Select one' ? Please help to sort
$(document).ready(function () {
$('#dav').val(getURLParameter('davQ'));
$('#pathogenQ').val(getURLParameter('pathogenQ'));
$('#topicQ').val(getURLParameter('topicQ'));
$(".selfont").change(function (event) {
window.location = '?davQ=' + $('#dav').val() + '&pathogenQ=' + $('#pathogen').val() + '&topicQ=' + $('#topicF').val();
});
function getURLParameter(name) {
return decodeURI((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]);
}
});
<?php
$test = mysql_query("SELECT DISTINCT DataVersion FROM olivesdeptable ORDER BY DataVersion DESC");
$i=1;
$selected = '';
// make compare with the value you want to select with the parameter form url
// here I assume $_GET['davQ'] holds the value to $numval['DataVersion']
if($_GET['davQ'] == $numval['DataVersion']) $selected = 'selected';
while($numval=mysql_fetch_array($test))
{
echo "<option value=\"".$numval['DataVersion']."\" $selected>".$numval['DataVersion']."</option>";
$i=$i+1;
}
?>

Categories