How to echo month dynamically according to year - php

I have following code
<?php
echo '<div class="row">
<div id="year" class="col-md-3 ">
<select id="year1" class = "form-control" name="year" onblur="sctMonth()">
<option id="1" value="" disabled selected>-- Year --</option>';
$year_query = "SELECT DISTINCT YEAR (uploaddate) AS OrderYear FROM billTable WHERE username='$log_username' ORDER BY uploaddate ASC ";
$result_year_query = mysqli_query($db_conx, $year_query);
echo $e2= mysqli_error($db_conx );
while ( $year_query = mysqli_fetch_row($result_year_query)){
$year_query = $year_query[0];
echo '<option value='.$year_query.'>'.$year_query.'</option>';
}
echo ' </select>
</div>';
echo '<div id="month" class="col-md-3 ">
<select id="month1" class = "form-control" name="month" >
<option id="1" value="" disabled selected>-- Month --</option>';
if(isset($_POST["monthcheck"])) {
include_once("php_includes/db_conx.php");
$year = preg_replace('#[^a-z0-9]#i', '', $_POST["monthcheck"]);//year options for month
$month_query = "SELECT DISTINCT MONTHNAME(uploaddate) AS OrderMONTH
FROM billTable
WHERE username='$log_username' AND year(uploaddate) = '$year'
ORDER BY uploaddate ASC ";
$result_month_query= mysqli_query($db_conx, $month_query);
while ( $month_query = mysqli_fetch_row($result_month_query)){
$month_query = $month_query[0];
//echo json_encode($month_query);
echo '<option value='.$month_query.'>'.$month_query.'</option>';
}
}
echo ' </select>
</div>
<span id="month1_status"></span></div>';
//echo $year ;
?>
What I am trying to do this when user selects year, month should be display accordingly using ajax, I send year to php using ajax but I can't figure out how to display month and refresh as year changes ,currently it just shows blank select box, Or is it better to pass month as array using json_encode($month_query); , but I don't know how to use it.

Not exactly what you want, but the code is quite unreadable. I recommend trying to write more readable because you'll thank yourself later.
I think is missing a piece of your code and explain better what is wrong with him
btw. here is a more readable version
<?php
$log_username = mysqli_real_escape_string($db_conx, $log_username);
$year_query = <<<SQL
SELECT DISTINCT YEAR(uploaddate) AS OrderYear
FROM billTable
WHERE username = "{$log_username}"
ORDER BY uploaddate ASC
SQL;
$query_year_result = mysqli_query($db_conx, $year_query);
$query_year_error = mysqli_error($db_conx);
$select_block = <<<HTML
<div class="row">
<div id="year" class="col-md-3">
<select id="year1" class="form-controler" name="year" onblur="sctMonth()">
<option id="1" value="" disabled selected>-- Year --</option>
YEAR_OPTIONS
</select>
</div>
<div id="month" class="col-md-3">
<select id="month1" class="form-controler" name="month">
<option id="1" value="" disabled selected>-- Month --</option>
MONTH_OPTIONS
</select>
</div>
<span id="month1_status"></span></div>
</div>
HTML;
$year_options = "";
if (!$query_year_error) {
while($row_year_query = mysqli_fetch_row($query_year_result)) {
$year = $row_year_query[0];
$year_options .= "<option value="{$year}"></option>";
}
}
$month_options = "";
if (isset($_POST['monthcheck'])) {
// I'll left this here commented because I dont know why are you calling here
// if you use $qb_conx before
// include_once("php_includes/db_conx.php");
$year = preg_replace('#[^a-z0-9]#i', '', $_POST["monthcheck"]);
$year = mysqli_real_escape_string($db_conx, $year);
$month_query = <<<SQL
SELECT DISTINCT MONTHNAME(uploaddate) AS OrderMONTH
FROM billTable
WHERE username = "{$log_username}" AND year(uploaddate) = "{$year}"
ORDER BY uploaddate ASC
SQL;
$query_month_result = mysqli_query($db_conx, $month_query);
$query_month_error = mysqli_error($db_conx);
if (!$query_month_result) {
while($row_month_query = mysqli_fetch_row($query_month_result)) {
$month = $row_month_query[0];
$month_options .= "<option value="{$month}">{$month}</option>";
}
}
}
$select_block = str_replace('YEAR_OPTIONS', $year_options, $select_block);
$select_block = str_replace('MONTH_OPTIONS', $month_options, $select_block);
echo $select_block;

Related

multiple <select> dropdown as sql parameters | PHP

I have a running code that does sql query based on 1 <select> dropdown value. May I ask how will I be able to do multiple query parameters using 2 or more <select> dropdown?
Example. I sorted my data based on accounttitle now I want to sort accountttitle by YEAR(datedue), how will I do this?
This is what I got so far.
For isset()
if(isset($_GET['accounttitle'])){
$accounttitle = $_GET['accounttitle'];
$year = date('Y');
if(isset($_GET['year'])){
$year = $_GET['year'];
}
else "PLEASE SELECT OPTION";
}
?>
For <select>
<div class="col-sm-9">
<select class="form-control" id="select_account_title" style="text-transform:uppercase" required>
<option value="">PLEASE SELECT OPTION</option>
<?php while ($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)): ?>
<option value="<?= urlencode($row['accounttitle'])?>"><?= $row['accounttitle'] ?></option>
<?php endwhile; ?>
</select>
<label>Select Year: </label>
<select class="form-control input-sm" id="select_year">
<?php
for($i=2013; $i<=2033; $i++){
$selected = ($i==$year)?'selected':'';
echo "
<option value='".$i."' ".$selected.">".$i."</option>
";
}
?>
</select>
</div>
For SQL
$sql = "SELECT referenceno, employeeidno, accounttitle, 'ON PROGRESS' as debit, postedby, approvedby, notedby, credit FROM earningsamendment where accounttitle= '$accounttitle' and YEAR(datedue)='$year'";
$query = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)){
This is my concern.
$(function(){
$('#select_account_title').change(function(){
window.location.href = 'earnings_amendment.php?accounttitle='+$(this).val();
});
});
</script>
How will I enable <script> to read 2 parameters? like
$(function(){
$('#select_account_title').change(function(){
window.location.href = 'earnings_amendment.php?accounttitle='+$(accounttitle).val()'&year='+$(year).val();
});
});
</script>
or something similar?
You need an on change with multiple selectors.
$(document).on('change', '#select_account_title, #select_year', function() {
var account_title = $("#select_account_title").val();
var year = $("#select_year").val();
window.location.href = 'earnings_amendment.php?accounttitle='+account_title+'&year='+year;
});

Search form with PHP and PDO then display results on page

I am trying to search my SQL database with a simple search form and then return the data to the screen.
For example, the user can select a year, then all the row results from the table display all of the information for that entry. Here is my form:
<form class="" method="POST" action="availability.php" enctype="multipart/form-data">
<select class="form-control mb-3" name="year" id="year">
<option disabled selected>Year</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
</select>
<input class="btn btn-blue-grey" type="submit" value="submit">Search
<i class="fas fa-search ml-1"></i>
</input>
</form>
And here is my PHP
if(isset($_POST['submit'])) {
$year = $_POST['year'];
var_dump($year);
var_dump($_POST);
$sql = "SELECT * FROM availability WHERE year = :year";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':year',$year,PDO::PARAM_STR);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
$data = $stmt->fetchAll(); }
and my HTML
<ul>
<?php foreach($data as $stmt) { ?>
<li><?php echo $stmt['cruise'];?></li>
<li><?php echo $stmt['year'];?></li>
<?php } ?>
</ul>
At the minute, the form submits, but I get nothing populating the list.. Any help would be appreciated.
You can try to use this query :
$year = $_POST['year'];
$sql = "SELECT * FROM availability WHERE year = :year";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':year',$year,PDO::PARAM_STR);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
$data = $stmt->fetchAll();
$stmt->bindParam(':year',$year,PDO::PARAM_STR); <-- does this need to be PARAM_INT ?
also have you var_dump'ed $year = $_POST['year']; to make sure you are getting a value?
You could turn on error_reporting and see if you get any useful errors
you must change a few thing,
first, edit the select tag to:
<select class="form-control mb-3" name="year" id="year">
<option disabled selected>Year</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
</select>
There is a condition that seems it is wrong.
so, change your html code to
if($_POST) {
$year = $_POST['year'];
$stmt = $pdo->prepare("SELECT * FROM availability WHERE year = :year");
$stmt->execute(array("%$year%"));
// fetching rows into array
$data = $stmt->fetchAll();}

not able to get values from database and updating values to the database

into schooling entry form, I am not able to get value of employee_id from post.
I did Print_r for $employee_id, blank output is rendered.
Also if allocated static value to $employee_id, $sum contains only value posted through the form, instead it should show the value from input form plus value from existing value available in database.
<?php
$get = db_query("SELECT field_employee_id_value FROM field_data_field_employee_id ORDER BY field_employee_id_value ASC");
$getempnames = db_query("SELECT field_employee_id_value FROM field_data_field_employee_id ORDER BY field_employee_id_value ASC");
if(isset($_POST['apply'])){
$sql = db_query("SELECT COUNT(id) as count_id FROM schooling WHERE employee_id = '$_POST[employee_id]' AND claim_year = '$_POST[claim_year]'");
$row = $sql->fetchAssoc();
if('1' == $row['count_id']){
$sqlupdate = db_query("UPDATE schooling SET limit_amount = '".$_POST['limit_amount']."' WHERE employee_id = '$_POST[employee_id]'");
echo "Schooling limit updated to user ";
} elseif ('0' == $row['count_id']){
$sqlinsrt = db_query("INSERT INTO schooling (employee_id, limit_amount, claim_year) VALUES ('".$_POST["employee_id"]."','".$_POST["limit_amount"]."','".$_POST["claim_year"]."')" );
echo "Schooling limit applied to user";
} else{
echo "Already Applied schooling limit";
}
}
if(isset($_POST['save'])){
$employee_id = $_POST['employee_id'];
$claim_amount = $_POST['claim_amount'];
$claim_year = $_POST['claim_year'];
$sqlchkemp = db_query("SELECT COUNT(id) as count_id FROM schooling WHERE employee_id = '$employee_id' AND claim_year = '$claim_year'");
$empavailable = $sqlchkemp->fetchAssoc();
if('1' == $empavailable['count_id']){
$getlimit = db_query("SELECT limit_amount FROM schooling WHERE employee_id = '$employee_id' AND claim_year = '$claim_year'");
$limit = $getlimit->fetchAssoc();
$getemptotalclaim = db_query("SELECT claim_amount FROM schooling
WHERE employee_id = '$employee_id' AND claim_year = '$claim_year'");
$emptotalclaim = $getemptotalclaim->fetchAssoc();
$totalclaimed = array_sum($emptotalclaim);
$availability = $limit['limit_amount'] - $_POST['claim_amount'];
$sum = $totalclaimed['claim_amount'] + $claim_amount;
if ($sum <= $limit['limit_amount']){
$sqlinsert = db_query("UPDATE schooling SET claim_amount = '$sum' WHERE employee_id = '$employee_id'");
echo "values updated successfuly";
}
else{
echo "limit is over, you can avail total amount ".$availability." as per ".$limit['limit_amount']." alloted";
}
}
else{
echo "employee schoolig limit is not set";
}
}
?>
<html>
<body>
<form id='applylimit' action='' method='post' accept-charset='UTF-8'>
<fieldset>
<label>Apply Schooling Limit amount to Employee</label>
<label for='employee_id'>Employee Id</label>
<select name='employee_id'>
<option value="0">Please Select</option>
<?php
while($row = $getempnames->fetchAssoc())
{
?>
<option value = "<?php echo($row['field_employee_id_value'])?>">
<?php echo($row['field_employee_id_value']) ?>
</option>
<?php
}
?>
</select>
<label for='limit_amount'>Limit Amount</label>
<input type='number' name='limit_amount' id='limit_amount' maxlength="50" />
<label for='claim_year'>Claim Year</label>
<select type='number' name='claim_year' id='claim_year' maxlength="50">
<option value="2018-19">2018-19</option>
<option value="2019-20">2019-20</option>
</select>
<button type="submit" name="apply">Apply</button>
</fieldset>
</form>
<form id='schoolingentry' action='' method='post' accept-charset='UTF-8'>
<fieldset>
<label for='employee_id'>Employee Id </label>
<select name='employee_id'>
<option value="0">Please Select</option>
<?php
while($rowemp = $get->fetchAssoc())
{
?>
<option value = "<?php echo($row['field_employee_id_value'])?>" >
<?php echo($rowemp['field_employee_id_value']) ?>
</option>
<?php
}
?>
</select>
<label for='claim_amount'>Claim Amount</label>
<input type='number' name='claim_amount' id='claim_amount' maxlength="50" />
<label for='claim_year'>Claim Year</label>
<select name='claim_year' id='claim_year' maxlength="50">
<option value = "2018-19">2018-19</option>
<option value = "2019-20">2019-20</option>
</select>
<button type="submit" name="save">save</button>
</fieldset>
</form>
</body>
</html>
word of warning, do not put anything submitted from a $_POST straight into a database query. You should sanitize it all by passing in the parameters.
e.g.
$result = db_query('SELECT n.name FROM users n WHERE n.name = :name', array(':name' => $name));
If the first query isn't returning any results, it's likely those two parameters you are passing into the string are not what you expect, or not valid. Try echoing out the two variables, then running the SQL query manually.
Or if you want Drupal to be a bit more verbose, wrap it in a exception catcher..
e.g.
catch (\PDOException $e) {
$error = $e->getMessage();

set default value in option select dropdown which the user selected php

First let's assume that the user has selected an ID to edit the specific data.
Here's where the user select to edit
Output will be here
But my problem is that it's not highlighting the specific data where the user need to edit and if the user save it the value will be 0 or null.
Error1 Error2
I want to highlight the specific data where the user need to edit like this one..
Hihglighted
I have 2 queries:
Here's are all my query to get the subject , semester/term and schoolyear:
$sql1 = "select * from subject";
$subject = $conn -> query($sql1);
$sql2 = "select * from sy";
$sy = $conn -> query($sql2);
$sql3 ="select * from term";
$semester = $conn -> query($sql3);
and here's my query to get the subject code and the subject description where the user select the id to edit..
$sql4 = "select subject.Subject_Description ,subject.Subject_Code, subject_offer.Subject_Offer_ID, term.Term_Name
from subject_offer
inner join subject on subject_offer.Subject_Code = subject.Subject_Code
inner join term on subject_offer.Term_ID = term.Term_ID
where subject_offer.Subject_Offer_ID = '$id'";
$result = $conn -> query($sql4)->fetch_object();
Here's the code for my dropdown or option select..
<div class="form-group row">
<label for="inputEmail3" class="col-sm-2 col-form-label">Subject</label>
<div class="col-sm-7">
<select class="form-control form-control-md col-sm-12" id="inputSmall" name="subject">
<option disabled selected ><?php echo $result->Subject_Code . '' .$result->Subject_Description ?></option>
<?php while($row1 = $subject->fetch_object() ): ?>
<option value="<?php echo $row1->Subject_Code ?>" >
<?php echo $row1->Subject_Code.' '.$row1->Subject_Description; ?>
</option>
<?php endwhile; ?>
</select>
</div>
</div>
There is no Term_ID in select clause of your second query. Also, you are missing value attribute in your disabled option. Should be:
<option disabled selected value="<?php echo $result->Subject_Code ?>">
<?php echo $result->Subject_Code . ' ' .$result->Subject_Description ?>
</option>
I usually do it differently, that is, mark the selected option when its value is the current one:
<select class="form-control form-control-md col-sm-12" id="inputSmall" name="subject">
<?php while($row1 = $subject->fetch_object() ): ?>
<option value="<?php echo $row1->Subject_Code ?>" <?= $row1->Subject_Code === $result->Subject_Code ? 'selected' : '' ?>>
<?php echo $row1->Subject_Code.' '.$row1->Subject_Description; ?>
</option>
<?php endwhile; ?>
</select>

Generating reports based on user input in php

I have a form to generate reports. In my form only the from_date and to_date fields are mandatory. If the user selects only from_date and to_date then I need to generate all the sales between those dates. If he/she wants to generate cash & credit wise or party wise or agent wise reports (these fields are on the right side of the form), then I should be able to generate reports customized that way also. I'm not able to write the logic to create the SQL query. Thank You!
HTML:
<form class="row" id="reports" style="width: 100%; margin-bottom: 1%">
<div class="pull-left clearfix">
<label for="from" class="lab-sm">From:</label>
<input type="date" id="from" name="from" value="<?php echo date("2016-09-20"); ?>">
<label for="to" class="lab-sm">To:</label>
<input type="date" id="to" name="to" value="<?php echo date("Y-m-d"); ?>">
<div>
<label for="to" class="lab-sm">Inv:</label>
<select name="purchase" id="purchase" class="inp-sm">
<option value="INV">All</option>
</select>
</div>
</div>
<div class="pull-right clear-left" style="position: relative;">
<div>
<select name="payment" id="payment" class="inp-lg">
<option value="">Cash & Credit Sales</option>
<option value="Cash">Cash</option>
<option value="Credit">Credit</option>
</select>
</div>
<div>
<select name="party" id="party" class="inp-lg">
<option value="">-- All Parties --</option>
<? $query = $con->query("SELECT la_head FROM ledger_accounts"); ?>
<? while($row = mysqli_fetch_array($query)) { ?>
<option value="<?php echo $row['la_head']; ?>"><? echo $row['la_head']; ?></option>
<? } ?>
</select>
</div>
<div>
<select name="agent" id="agent" class="inp-lg">
<option value="">-- All Agents --</option>
<? $query = $con->query("SELECT la_agent FROM ledger_accounts"); ?>
<? while($row = mysqli_fetch_array($query)) { ?>
<option value="<?php echo $row['la_agent']; ?>"><? echo $row['la_agent']; ?></option>
<? } ?>
</select>
</div>
<!-- submission -->
<div style="position: relative; left: 44px">
<input type="submit" value="Generate">
<input type="hidden" name="reports" value="sales_reports">
</div>
</div>
</form>
PHP:
if (ISSET($_POST['reports']) && $_POST['reports'] === 'sales_reports') {
$from_date = $con->real_escape_string($_POST['from']);
$to_date = $con->real_escape_string($_POST['to']);
$payment_type = $con->real_escape_string($_POST['payment']);
$party = $con->real_escape_string($_POST['party']);
$agent = $con->real_escape_string($_POST['agent']);
$query = "SELECT *
FROM sales
INNER JOIN ledger_accounts ON sales.la_id = ledger_accounts.la_id
INNER JOIN inventory_items ON sales.item_no = inventory_items.item_no
WHERE inv_date >= ? AND inv_date <= ?
AND sales.payment_type = COALESCE(?, sales.payment_type)
AND ledger_accounts.la_head = COALESCE(?, ledger_accounts.la_head)
AND ledger_accounts.la_agent = COALESCE(?, ledger_accounts.la_agent)";
$stmt = $con->prepare($query);
$stmt->bind_param('sssss', $from_date, $to_date, $payment_type, $party, $agent);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>'.$row['inv_date'].'</td>';
echo '<td>'.$row['inv_no'].'</td>';
echo '<td>'.$row['la_head'].'</td>';
echo '<td>'.$row['la_address'].'</td>';
echo '</tr>';
}
If you are expecting that you may not get a value for all parameters, you can do the following using COALESCE():
$query = "SELECT *
FROM sales
INNER JOIN party ON sales.party_id = party.party_id
INNER JOIN items ON sales.item_no = items.item_no
WHERE inv_date >= ? AND inv_date <= ?
AND payment_type = COALESCE(?,payment_type)
AND party = COALESCE(?,party)
AND agent = COALESCE(?,agent);";
$statement = $dbConn->prepare($query);
$statement->bind_param('sssss',$from_date,$to_date,$payment_type,$party,$agent);
COALESCE() works by providing the first non-null value. So, if the parameter passed in is NULL, then the above will just match whatever is in the field you are filtering on (party = party).
You want to parameterize you query, too, as to avoid potential SQL-injection attacks. I have applied that to the code above as well.
Good resources:
http://php.net/manual/en/mysqli-stmt.bind-param.php
How can I prevent SQL injection in PHP?

Categories