Generating reports based on user input in php - 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?

Related

Display unlimited row by random ID selected by user (created by php)

I need to display row from different table with random id that what i make it php generate it when i add new car or new driver
For example :
In this image table record's for same driver and different Car
and in this image the records for random id for the car
I need to show every records by date for same driver and Which car he use
Note: In this case its show like this
and I need it show like this
and sorry for arabic database records tell me if there anything not understood
my code:
<?php
require 'config.php';
$query = "SELECT * FROM `driversuser`";
$result1 = mysqli_query($con, $query);
?>
<div class="container">
<div class="addingcar">
<form dir="rtl" action="#" method="post">
<div class="">
<b>عرض وردية سائق</b>
</div>
<br/>
<label>
<b>اختر السائق</b>
<select name="insdname" id="framework" class="align-right selectpicker" data-live-search="true">
<option style="text-align: right" value="">اختر السائق ...</option>
<?php while($row1 = mysqli_fetch_array($result1)):; ?>
<option style="text-align: right" value="<?php echo $row1[10]; ?>"><?php echo $row1[1]; ?></option>
<?php endwhile; ?>
</select>
</label>
<br />
<label>
<b>من</b>
<input type="date" name="datefrom">
</label>
<br />
<label>
<b>الي</b>
<input type="date" name="dateto">
</label>
<br /><br />
<input type="hidden" name="hidden_framework" id="hidden_framework" />
<input type="submit" name="submit" class="btn btn-info" value="عــــرض" />
</form>
<?php
if(isset($_POST['submit'])){
$selected_val = $_POST['insdname'];
$date_val = $_POST['datefrom'];
$dateto_val = $_POST['dateto'];
$report = mysqli_query($con, "SELECT * FROM `reports` WHERE Datefrom BETWEEN '$date_val' AND '$dateto_val' AND DriverCode = '$selected_val' ORDER BY Datefrom");
while ($datareport = mysqli_fetch_array($report)) {
echo $datareport['Datefrom']." ".$datareport['DateTo']." ".$datareport['Price']." ".$datareport['PriceTaken']." ";
$report2 = mysqli_query($con, "SELECT * FROM `reports` WHERE DriverCode = '$selected_val' GROUP BY CarCode");
while ($datareport2 = mysqli_fetch_array($report2)) {
$carcode = $datareport2['CarCode'];
}
$report3 = mysqli_query($con, "SELECT * FROM `cars` WHERE Car_ID = '$carcode'");
while ($datareport3 = mysqli_fetch_array($report3)) {
echo $datareport3['CarName']." ".$datareport3['CarModel']." ".$datareport3['CarNumber']." ".$datareport3['CarColor']." ";
echo '<br/>';
}};
}
?>
</div>
</div>
I don't have your database schema, but I tried to create one for testing. So, try this:
SELECT * FROM reports r1 INNER JOIN cars c1 ON r1.carcode = c1.car_id ORDER BY r1.date
r1 is a shortcut for reports table ( change it to whatever you like ).
c1 is a shortcut for cars table ( also, you can change it ).
You can read more about INNER JOIN.

How to used selected in dropdown list

i dont know exactly how i am supposed to explain my question. but i'll try my best. Im currently trying to make an update form. when user clicked on the edit icon they will be directed to the edit form and the value are carried. i used 'typeid' to carry the values. im having problem with my drop down. i used selected but the value duplicate.
dropdown
so im trying to solve this, but know idea how to solve it. i have to used php only and i am not an expert of php.
if (isset($_GET['typeid'])) {
$sql = "SELECT * FROM vehicletype WHERE id_vehicleType=" . $_GET['typeid'];
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
if($row['status_vehicleType']==1){
$status = "Enabled";
}
else{
$status = "Disabled";
}
}
above are the typeid that i used to carry the values.
<div class="form-group">
<label>Choose Vehicle Type Status</label>
<select class="form-control" name="status" required class="form-control" value="<? php if(isset($row['status_vehicleType'])){ echo $status; } ?>">
<option value="">Select Vehicle Type</option>
<option value=<?php echo $row['status_vehicleType']; ?> <?php if($_GET["typeid"]==$row['status_vehicleType']){ ?> selected <?php } ?> ><?php echo $status; ?></option>
<option value="1">Enabled</option>
<option value="0">Disabled</option>
</select>
Here is simple answer for this question
if you have any other questions freely ask me thanks
<?php
function selected($x, $y) {
if ($x == $y) {
return " selected";
} else {
return "";
}
}
$sql = "SELECT * FROM vehicletype WHERE id_vehicleType=" . $_GET['typeid'];
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
$q_status = $row['status_vehicleType'] ;
?>
<div class="form-group">
<label class="control-label text-inverse" for="name">Status</label>
<select class="form-control" name="q_status" id="q_status" required="" autocomplete="off" >
<option value="1" <?php echo selected($q_status,"1");?> >Enabled</option>
<option value="0" <?php echo selected($q_status,"0");?> >Disabled</option>
</select>
</div>
use below code, (for testing set $_GET['typeid']=somevalue):
$row=array();
if (isset($_GET['typeid'])) {
$sql = "SELECT * FROM vehicletype WHERE id_vehicleType=" . $_GET['typeid'];
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
}
<div class="form-group">
<label>Choose Vehicle Type Status</label>
<select class="form-control" name="status" required class="form-control">
<option value="">Select Vehicle Type</option>
<option value="1" <?php if($row['status_vehicleType']==1){?>selected<?php }?>>Enabled</option>
<option value="0" <?php if($row['status_vehicleType']==0){?>selected<?php }?>>Disabled</option>
</select>

How to add to this update SQL statement and make a drop down list too for it

Okay i have this SQL statement for update which works find but I want to add locations which is in te_venue table after adding the location into sql i want for locations to be a drop down list which user can pick one location from list and when clicked on update it should update.
This is the php code that I have already (I need to add location into this)
<?php
$eventID = $_GET['id'];
if(isset($_POST['submit']))
{
$title = $_POST['title'];
$startdate = $_POST['startdate'];
$enddate = $_POST['enddate'];
$price = $_POST['price'];
$description = $_POST['description'];
$sql = "UPDATE te_events SET eventTitle='$title',eventStartDate='$startdate',eventEndDate='$enddate',eventPrice='$price',eventDescription='$description' WHERE eventID=$eventID";
if ($conn->query($sql) === TRUE)
{
header('Location:edit.php');
}
else
{
echo "Error updating record";
}
}
$sql = "SELECT * FROM te_events where eventID='$eventID'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
$eventTitle = $row['eventTitle'];
$eventDescription = $row['eventDescription'];
$eventStartDate = $row['eventStartDate'];
$eventEndDate = $row['eventEndDate'];
$eventPrice = $row['eventPrice'];
}
?>
And this is where i want to have a drop down list for location.
<form method="post" action="">
<label for="title">Title</label><br/>
<input type="text" name="title" required/ value="<?php echo $eventTitle; ?>"><br/>
<label for="startdate">Start Date</label><br/>
<input type="date" name="startdate" required/ value="<?php echo $eventStartDate; ?>"><br/>
<label for="enddate">End Date</label><br/>
<input type="date" name="enddate" required/ value="<?php echo $eventEndDate; ?>"><br/>
<label for="price">Price (£)</label><br/>
<input type="number" step="any" name="price" required/ value="<?php echo $eventPrice; ?>"><br/>
<label for="description">Description</label><br/>
<textarea name="description" cols="55" rows="5"><?php echo $eventDescription; ?></textarea><br/>
<input type="submit" name="submit" value="Update" class="button">
</form>
Here is a screenshot of my tables too it might help.
https://postimg.org/image/6ui8nsi55/
Do you want something like this? Getting the location from te_venue and adding the results to a select?
<select>
<?php
$sql = "SELECT location FROM te_venue";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
}
?>
<option value="<?php echo $row['location'];?>"><?php echo $row['location'];?> </option>
<?php
}
?>
</select>
<label for="location">Choose a location: </label>
<select class="form-control" name="location">
<option value="London">London</option>
<option value="Paris">Paris</option>
<option value="Rome">Rome</option>
<option value="Berlin">Berlin</option>
<option value="Moscow">Moscow</option>
</select>

How to echo month dynamically according to year

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;

Populating select box with existing value

I have created a form which allows users to edit existing data within a database, I pull information from one page to the next to populate text boxes and select boxes. I have managed to populate the select box with the correct value but when the update statement goes through it deletes or doesn't recognize the pre-existing value. Can anyone help?
if (isset($_POST['submit'])) {
// Process the form
if (empty($errors)) {
$id = $brand["brandId"];
$brandName = mysql_prep($_POST["brandName"]);
$brandCategory = mysql_prep($_POST["brandCategory"]);
$brandKeyword = mysql_prep($_POST["brandKeyword"]);
$addedBy = mysql_prep($_SESSION['username']);
$query = "UPDATE brands SET ";
$query .= "brandName = '{$brandName}', ";
$query .= "brandCategory = '{$brandCategory}', ";
$query .= "brandKeyword = '{$brandKeyword}', ";
$query .= "addedBy = '{$addedBy}', ";
$query .= "dateTime = CURRENT_TIMESTAMP ";
$query .= "WHERE brandId = '{$id}' ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) == 1) {
// Success
$_SESSION["message"] = "Brand updated.";
redirect_to("search.php");
} else {
// Failure
$_SESSION["message"] = "Brand update failed.";
}
}
} else {
// This is probably a GET request
} // end: if (isset($_POST['submit']))
?>
<?php $layout_context = "user"; ?>
<?php include("../includes/layouts/header.php"); ?>
<?php include("../includes/layouts/navigation.php"); ?>
<div class="section">
<div id="message">
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
</div>
<form id="edit_brands" action="edit_brands.php?id=<?php echo urlencode($brand["brandId"]); ?>" method="post">
<h2>Edit Brand Information: <?php echo htmlentities($brand["brandName"]);?></h2>
<p>
<label for="bname">Brand Name:</label>
<input class="textbox" id="bname" type="text" name="brandName" value="<?php echo htmlentities($brand["brandName"]); ?>" autofocus/>
</p>
<p>
<label for="bcategory">Brand Category:</label>
<select class="textbox" id="bcategory" type="text" name="brandCategory">
<option value=""><?php echo htmlentities($brand["brandCategory"]); ?></option>
<option value="Animation">Animation</option>
<option value="Automotive">Automotive</option>
<option value="Beauty and Fashion">Beauty & Fashion</option>
<option value="Comedy">Comedy</option>
<option value="Cooking and Health">Cooking & Health</option>
<option value="DIY">DIY</option>
<option value="Fashion">Fashion</option>
<option value="Film and Entertainment">Film & Entertainment</option>
<option value="Food and Drink">Food & Drink</option>
<option value="Gaming">Gaming</option>
<option value="Lifestyle">Lifestyle</option>
<option value="Music">Music</option>
<option value="News and Politics">News & Politics</option>
<option value="Science&Education">Science & Education</option>
<option value="Sports">Sports</option>
<option value="Technology">Technology</option>
<option value="Television">Television</option>
</select>
</p>
<p>
<label for="bkeyword">Brand Keyword:</label>
<textarea class="FormElement" id="bkeyword" name="brandKeyword" id="brandKeyword" placeholder=""><?php echo htmlentities($brand["brandKeyword"]); ?></textarea>
</p>
<p>
<input type="submit" class="button" name="submit" value="Edit Brand" onclick="return confirm('Do you wish to edit brand?');"/>
</p>
<p>
Cancel
</p>
</form>
</div>
</div>
The best way is to build the select from an array.
For instance:
<?php
$array = array('Animation', 'Automotive', 'Beauty and Fashion ', ...);
echo '<select class="textbox" id="bcategory" type="text" name="brandCategory">';
foreach ($array as $value){
if($value == htmlentities($brand["brandCategory"]){
echo '<option value='.$value.' selected>'.$value.'</option>';
}else{
echo '<option value='.$value.'>'.$value.'</option>';
}
}
echo '</select>;
This way you can check if the value in the array is the same that the one recieved by post and then add the selected attribute to the option tag.

Categories