PHP Show options depending on the selected year - php

I am trying to show options to the user according to the year he's selecting.
At the top of the file I have a function to retrieve the year, and send it back to the same page which is view2.php, but I'm sure I'm doing it wrong:
if(!empty($_POST['year'])){
$year = htmlentities($_POST['year']);
header('Location: view2.php');
//exit();
}
Later, I have a form submitting the year that looks like this
<form method="post" action="">
Select year:
<?php
$myOptions = array(
'All' => 'All',
'2013' => '2013',
'2014' => '2014',
'2015' => '2015',
'2016' => '2016',
'2017' => '2017',
'2018' => '2018',
'2019' => '2019',
'2020' => '2020'
);
?>
<select name="year">
<?php
foreach($myOptions as $key => $opt) {
$selected = null;
if(isset($_POST['View All']) && $key === $_POST['View All'])
$selected = ' selected';
echo '<option value="' . $key . '"' . $selected. '>' . $opt . '</option>';
}
?>
</select>
<input type="submit" name="submit" value="GO"/>
</form>
If I manually set the $year variable, my sql query works fine, so the function ($users->expensePerYear($username, $year, $i);) is okay. This is my function:
<?php
$i=0;
$year = 2013;
//if (isset($year)){
$users->expensePerYear($username, $year, $i);
$userQueryResult = $users->queryResult;
$count = $users->i;
$totalSpent = $users->totalSpent;
$remaining = $budget-$totalSpent;
The problem is that I'm trying to send the year variable to the same page and I'm doing it wrong. I want the user to specify the year in the select, send it to the same page and show stuff according to that variable.

Never mind me, I only had to comment the header() line and it works.
if (isset($_POST['submit2'])) {
$year = htmlentities($_POST['year']);
//header('Location: view2.php?$year=".$year."');
//echo $year;
}

Related

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

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>

Generate dropdown menu dynamically and change php variables on option select

I am trying to get dropdown menu to set a value to a php variables on option selected. I can print the menu dynamically with the code below:
<?php
$option_to_preselect = $package_name;
$ddown_options = $package_name;
$arrlength = count($ddown_options);
print '<select name = "package" id = "pack_select" class="select-submit2">';
for ($i=1; $i < $arrlength; $i++)
{
if ($ddown_options[$i]==$option_to_preselect)
{
print ' <option value ="' . $ddown_options[$i] . '"' . ' selected ="selected">' . $ddown_options[$i] . '</option>';
$packageID = $i;
$packagePrice = $packages_price[$i];
} else {
print ' <option value="' . $ddown_options[$i] . '">' . $ddown_options[$i] . '</option>';
$packageID = $i;
$packagePrice = $packages_price[$i];
}
}
print '</select>';
?>
Then when the user selects an option, the variables $packageID and $packagePrice should obtain the id and the amount of the selected package.
The idea is to pass the values in a href where the href is:
href="<?php echo site_url('package_purchase/'.$lang_code.'/'.$packageID.'/'.$packagePrice); ?>"
The output of the $package_name is:
array (size=4)
'' => string '' (length=0)
1 => string 'Free' (length=4)
2 => string 'Basic' (length=5)
3 => string 'Premium' (length=7)
and the result of the code looks like:
<select name="package" id="pack_select" class="select-submit2">
<option value="Free">Free</option>
<option value="Basic">Basic</option>
<option value="Premium">Premium</option>
</select>

Zabuto Calendar with ajax

How can I get the events stored in my db to show in the calendar ?
I can't seem to figure out how to replace the random dates with my own ones :/
Basically I have to loop through the data i get from my db don't I ?
And put the data in the JSON format ...
Can I use a foreach loop ?
this is the code provided by the zabuto calendar download site
<?php include_once 'includes/sessions.php'; ?>
<?php include_once 'includes/connect.php';
/**
* Example of JSON data for calendar
*
* #package zabuto_calendar
*/
if (!empty($_REQUEST['year']) && !empty($_REQUEST['month'])) {
$year = intval($_REQUEST['year']);
$month = intval($_REQUEST['month']);
$lastday = intval(strftime('%d', mktime(0, 0, 0, ($month == 12 ? 1 : $month + 1), 0, ($month == 12 ? $year + 1 : $year))));
$dates = array();
for ($i = 0; $i <= (rand(4, 10)); $i++) {
$date = $year . '-' . str_pad($month, 2, '0', STR_PAD_LEFT) . '-' . str_pad(rand(1, $lastday), 2, '0', STR_PAD_LEFT);
$dates[$i] = array(
'date' => $date,
'badge' => ($i & 1) ? true : false,
'title' => 'Example for ' . $date,
'body' => '<p class="lead">Information for this date</p><p>You can add <strong>html</strong> in this block</p>',
'footer' => 'Extra information',
);
if (!empty($_REQUEST['grade'])) {
$dates[$i]['badge'] = false;
$dates[$i]['classname'] = 'grade-' . rand(1, 4);
}
if (!empty($_REQUEST['action'])) {
$dates[$i]['title'] = 'Action for ' . $date;
$dates[$i]['body'] = '<p>The footer of this modal window consists of two buttons. One button to close the modal window without further action.</p>';
$dates[$i]['body'] .= '<p>The other button [Go ahead!] fires myFunction(). The content for the footer was obtained with the AJAX request.</p>';
$dates[$i]['body'] .= '<p>The ID needed for the function can be retrieved with jQuery: <code>dateId = $(this).closest(\'.modal\').attr(\'dateId\');</code></p>';
$dates[$i]['body'] .= '<p>The second argument is true in this case, so the function can handle closing the modal window: <code>myFunction(dateId, true);</code></p>';
$dates[$i]['footer'] = '
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="dateId = $(this).closest(\'.modal\').attr(\'dateId\'); myDateFunction(dateId, true);">Go ahead!</button>
';
}
}
echo json_encode($dates);
} else {
echo json_encode(array());
}

users near a specific zip code: PHP mysql

Happy new year! Suppose user1 is located at zip code 12345. I want to find other users within X miles from that zip code.
First, I created the form:
<div id="wrapper">
<form action="L1.php" method="post">
<select name="radius">
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
Miles within Zip Code:
<input name="zip" type="text" value="13126" />
<input type="submit" value="refine" />
</form>
</div>
Now I am listing all the zip codes within X miles from 12345: (L1.php):
<?php
include('includes/db_AF.php'); //includes the db credentials
$connection = #new mysqli(HOSTNAME, MYSQLUSER, MYSQLPASS, MYSQLDB);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//look up the zip code in the searchbox
$whereClauses = array();
if (! empty($_POST['zip'])) $whereClauses[] ="zip_code='".mysqli_real_escape_string($connection,$_POST['zip'])."'";
$where = '';
if (count($whereClauses) > 0) { $where = ' WHERE '.implode(' AND ',$whereClauses); }
$sql = "SELECT * FROM zip " .$where." ";
$result=mysqli_query($connection,$sql) or die("Error: ".mysqli_error()."<br />Query: ".$sql);
//find out the corresponding lat and long
while ($row = mysqli_fetch_assoc($result)) {
echo '<br />';
echo '<br />';
$lat=$row['latitude'];
echo '<br />';
$lon=$row['longitude'];
echo '<br />';
}
$radius=$_POST['radius'];
//here I am generating an array of all the zip codes within x miles from 12345.
$query="SELECT * FROM zip WHERE (3958*3.1415926*sqrt((latitude-'$lat')*(latitude-'$lat') + cos(latitude/57.29578)*cos('$lat'/57.29578)*(longitude-'$lon')*(longitude-'$lon'))/180) <= '$radius'";
$result_obj = '';
$result_obj = $connection->query($query);
while($resultx = $result_obj->fetch_array(MYSQLI_ASSOC)) {
$items[] = $resultx;
}
foreach ($items as $item) {
echo $item['zip_code'];
echo '<br />';
}
$queryz="SELECT zip FROM customer"; // I am generating an array of all customer zip codes.
$resultz_obj = '';
$resultz_obj = $connection->query($queryz);
while($resultzz = $resultz_obj->fetch_array(MYSQLI_ASSOC)) {
$itemsz[] = $resultz;
}
$resultv = array_intersect($items, $itemsz);
print_r($resultv);
So now I have an array of zip codes. I want to list users that live at those zip codes. I know I have to intersect two arrays but get "Notice: Array to string conversion" error. Any thoughts?
If You have zip code in $items then i think you don't need $itemsz for all customer zipcodes.
First you need to format $items array to like this :
$zips = (12345,12346,12347,12348)
Then just run a query like this in customer:
Select * from customer where customer.zipcode IN $zips
demo: https://eval.in/84652
SAMPLE code:
$items =array( '0' => array( 'zip_code' => 13121, 'latitude' => 43.483379, 'longitude' => -76.315044, 'city' => 'New Haven', 'state' => 'NY', 'county' => 'Oswego' ), '1' => array( 'zip_code' => 13126, 'latitude' => 43.465388 ,'longitude' => -76.342172 ,'city' => 'Oswego' ,'state' => 'NY', 'county' => 'Oswego' ) );
$strzipCodes="";
foreach($items as $item){
$strzipCodes .= $item['zip_code']." ,";
}
$strzipCodes = rtrim($strzipCodes,',');
$sql ="SELECT * FROM customer where zip IN(".$strzipCodes.")";
echo $sql;
// then execute query we will get all users inside those zipcodes
I think you get the idea.

Looping through a drop down, how to select value?

When displaying a form on a page for a user to edit information, and the form consists of a drop down box, how do you loop through the selections in the dropdown box to select their predefined mySQL entry?
For example
Users country: Australia
How would I go about searching through a list of countries ie: http://snipplr.com/view/4792/country-drop-down-list-for-web-forms/ to make:
<option value="AU">Australia</option>
become
<option value="AU" selected="selected">Australia</option>
You could do something like:
<?php
$countries = array('AU' => 'Australia', 'AF' => 'Afghanistan', ...);
$selected = 'AU';
foreach ($countries as $code => $label) {
echo '<option value="' . $code . '"';
if ($selected == $code) {
echo ' selected="selected"';
}
echo '>' . $label . '</option>';
}
?>
Not the prettiest but you get the idea. As Shakti suggests, it's also easier to maintain if the values are in the DB and not in a massive array in the middle of the code.
Could be something like this:
<?php
//your query here
$sql = "SELECT * FROM countries ORDER BY code ASC";
$result_set = $database->query($sql);
while($country = $database->fetch_array($result_set)) {
if ($country["code"] == "AU"){
echo "<option value=\"{$country['code']}\" selected=\"selected\">{$country['name']}</option>";
}
else {
echo "<option value=\"{$country['code']}\">{$country['name']}</option>";
}
?>

Categories