How Make reports with specific range of dates in mysql - php

I am already using a daily report of the income of the store, but I need my report to do the following: i want to see the income report of specific range of dates, or weeks, or months.... essentially that i can choose which days or range of days i want see so i can print my selection.
here is inc.php
<?
$dbtype = "mysql";
$dbhost = "localhost";
$dbname = "anillos";
$dbuser = "rubi";
$dbpass = "----";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$conn->exec("set names utf8");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
?>
here is my code:
<table class="table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Fecha</th>
<th>Total Anillos Vendidos</th>
<th>Total ganado del día</th>
</tr>
</thead>
<tbody id="result_fechas">
<tr>
<?
include 'inc.php';
$sql = $conn->prepare("SELECT DATE(start) AS date, COUNT(id_anillos) AS total_anillos, SUM(ventas) AS total_diario_ganado
FROM PRODUCTOS WHERE start >= CURDATE() AND start < CURDATE() + INTERVAL 1 DAY ORDER BY start ASC");
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
?>
<td class="center"><? echo $row['date']; ?></td>
<td class="center"><? echo $row['total_anillos']; ?></td>
<td class="center"><? echo $row['total_diario_ganado']; ?></td>
</tr> <? } ?>
</tbody>
can you help me with this..I really not have a clue...
----UPDATE-----
# Chris78 I made this form:
<form name="fechas" id="fechas" method="post" >
<fieldset>
<legend>Reporte desde : </legend>
<input type="text" value="" placeholder="YYYY-MM-DD" name="f_desde" id="datepicker"/>
<legend>Reporte hasta : </legend>
<input type="text" value="" placeholder="YYYY-MM-DD" name="f_hasta" id="datepicker2" />
<button class="btn btn-inverse" type="submit" name="enviar" >
<i class="icon icon-print icon-white"></i>
Ver Reporte </button>
</fieldset>
</form>
the new SELECT CODE:
<?
$sql = $conn->prepare("SELECT DATE(start) AS date, COUNT(id_anillos) AS total_anillos, SUM(ventas) AS total_ganado FROM PRODUCTOS WHERE start BETWEEN 'f_desde' AND 'f_hasta' ORDER BY start ASC");
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
?>
the table :
<table class="table-bordered table-striped table-condensed">
<thead>
<tr>
<th>rango de fechas seleccionado</th>
<th>Total Anillos Vendidos</th>
<th>Total ganado</th>
</tr>
</thead>
<tbody id="result_fechas">
<tr>
<?
////////SELECT CODE HERE
?>
<td class="center"><? echo $row['date']; ?></td>
<td class="center"><? echo $row['total_anillos']; ?></td>
<td class="center"><? echo $row['total_ganado']; ?></td>
</tr> <? } ?>
</tbody>
and I am try to show the result with ajax call in the same page
<script type="text/javascript">
$(function(){
$("#fechas").submit(function(){
$.ajax({
type:"POST",
url:".reportes.php?ts=" + new Date().getTime(),
dataType:"text",
data:$(this).serialize(),
beforeSend:function(){
$("#loading").show();
},
success:function(response){
$("#result_fechas").append(response);
$("#loading").hide();
}
})
return false;
});
});
});
</script>
reportes.php is the same page where is the form and the table which is waiting the result....but I don´t know where is the error, because not catch ajax the data and the page is refreshing when I clic the button...can you help me with this.

If you are wanting to run a query with a date range you can use the BETWEEN statement.
$sql = $conn->prepare("SELECT DATE(start) AS date, COUNT(id_anillos) AS total_anillos, SUM(ventas) AS total_diario_ganado
FROM PRODUCTOS WHERE start BETWEEN 'Older Date Here' AND 'Newer Date Here' ORDER BY start ASC");

You create a form with those two inputs that you talked about, when you retrieve the input value you give the treatment "date('Y-m-d', inputvalue)" if it isn't already treated. Then you replace "CURDATE()" on you sql statement for the treated inputvalues.
Dates should always be given in the "yyyy-mm-dd" format to MySql.
Source: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-types.html

Related

Datatables PHP MYSQL - How to display specific entries

I have a database with the following columns:
(okladka, imie, nazwisko, tytul, rodzaj, info, download, data)
My DB name: serwer144221_SwiatBook
Table name: bazaplikow
In the value "rodzaj" each entry contains one word: "audiobook" or "ebook"
I would like to display in the table only those entries where the word in "ebook" appears.
How to read all rows from a database table where the column "rodzaj" contains a value "ebook"
This is my Source Code Datatables:
<?php
$servername = "xyz";
$username = "xyz";
$password = "xyz";
$database = "serwer144221_SwiatBook";
// Create connection
$connection = new mysqli($servername, $username, $password, $database);
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
// read all row from database table
$sql = "SELECT DISTINCT rodzaj * FROM bazaplikow";
$result = $connection->query($sql);
if (!$result) {
die("Invalid query: " . $connection->error);
}
?>
<section class="section-1">
<h3 align="center">Baza plików</h3>
<br />
<div class="table-responsive">
<table id="bazaplikow_data" class="table table-striped table-bordered" width="100%";>
<thead>
<tr>
<td align="center">Okładka</td>
<td align="center">Imię</td>
<td align="center">Nazwisko</td>
<td align="center">Tytuł</td>
<td align="center">Rodzaj</td>
<td align="center">Info</td>
<td align="center">Download</td>
<td align="center">Data</td>
</tr>
</thead>
<?php
while($row = mysqli_fetch_array($result))
{
echo '
<tr>
<td align="center"><img src="'.$row["okladka"].'" width="98" height="128"></td>
<td align="center">'.$row["imie"].'</td>
<td align="center">'.$row["nazwisko"].'</td>
<td align="center">'.$row["tytul"].'</td>
<td align="center">'.$row["rodzaj"].'</td>
<td align="center"><i class="fa fa-info-circle" aria-hidden="true"></i></td>
<td align="center"><i class="fa fa-download" aria-hidden="true"></i></td>
<td align="center">'.$row["data"].'</td>
</tr>
';
}
?>
</table>
</div>
</section>
<script>
$(document).ready(function () {
$('#bazaplikow_data').DataTable({
order: [[7, 'desc']],
});
});
</script>
Your query is wrong it should be
SELECT * from bazaplikow where rodzaj = 'ebook';

How to display mysql data in different HTML elements by using AJAX

I'm new to web development and I'm following a couple of tutorials. I'm learning that how to display mySQL data into HTML by using HTML, PHP, jQuery and AJAX. Below example is my practice work where I'm successfully loading data into HTML table.
<table id="main" border="1px" cellspacing="0">
<tr>
<td id="header">
<h1>PHP with AJAX</h1>
</td>
</tr>
<tr>
<td id="table-form">
<form id="addform">
Student First Name: <input type="text" id="st-first-name">
Student Last Name: <input type="text" id="st-last-name">
<input type="submit" value="Save Data" id="save-data"><br>
</form>
</td>
</tr>
<tr>
<td id="table-data">
<table border="1px" width="100" cellspacing="0px" cellpadding="10px">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr>
<td align="center">1</td>
<td>Abid Durrani </td>
</tr>
</table>
</td>
</tr>
</table>
Here is my AJAX Code.
$("document").ready(function(){
function loadData(){
$.ajax({
url: "ajaxload.php",
type: "post",
success: function(data){
$("#table-data").html(data);
}
});
} });
And this is my ajaxload.php code:
$myConn = mysqli_connect("localhost", "root", "", "test") or die("Your Connection Failed");
$sqlQuery = "select * from students";
$result = mysqli_query($myConn, $sqlQuery) or die ("Your Query Execution Failed");
$output = "";
if(mysqli_num_rows($result) > 0) {
$output = "
<table border='2' cellpadding='5px' cellspacing='5px'>
<tr>
<th width='100px'>ID</th>
<th>Name</th>
<th width='100px'>Delete</th>
</tr>";
while($row = mysqli_fetch_assoc($result)){
$output .= "
<tr>
<td>{$row['st_id']}</td>
<td>{$row['st_first_name']}</td>
<td><button class='btn-delete' data-myid={$row['st_id']}>Delete</button></td>
</tr>";
}
$output .= "</table>";
mysqli_close($myConn);
echo $output;
} else
{
echo "sorry, no record found";
}
Question: Here my data is directly loading into HTML table through its css ID. What I want is to set my database data into a textBox and a dropDownMenu along with this table. For table, I've created the table in ajaxload.php but what do I need to do for dropDownMenu and textBox?
Thanks.

php mysql database get price total [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
I have using php code with mysql database showing data into html table, and i'm using filter on listview, now I'm stack with get price Total of the list after filtered. I'm not good enough with php code, am I made mistake with php or sql?
MySQL table:
id INT -
name VARCHAR -
code VARCHAR -
price INT
here is my code so far:
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `toy` WHERE CONCAT(`id`, `name`, `code`, `price`)
LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `toy` LIMIT 5";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "user", "pass",
"database");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Wu</title>
<link href="style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="toys-grid">
<div class="search-box">
<br>
<form action="index.php" method="post">
<input type="text" name="valueToSearch" placeholder="Name To Search">
<br><br>
<input type="submit" name="search" value="Filter"><br><br>
</div>
<table cellpadding="10" cellspacing="1">
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Code</th>
<th>Price</th>
</tr>
</thead>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tbody>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['code'];?></td>
<td><?php echo $row['price'];?></td>
</tr>
</tbody>
<?php endwhile;?>
<thead>
<tr>
<th> Total </th>
<th>
<?php
$results = mysql_query('SELECT SUM(price) FROM toy');
$results->execute();
for($i=0; $rows = $results->fetch(); $i++){
echo $rows['SUM(price)'];
}
?>
</th>
</tr>
</thead>
</table>
</form>
</div>
</body>
I appreciate your help...
No need to execute query for getting sum. You can do it with php
<table cellpadding="10" cellspacing="1">
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Code</th>
<th>Price</th>
</tr>
</thead>
<!-- populate table from mysql database -->
<?php $sum = 0; ?>
<?php while($row = mysqli_fetch_array($search_result)):?>
<tbody>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['code'];?></td>
<td><?php echo $row['price'];?></td>
<?php
$sum += $row['price'];
?>
</tr>
</tbody>
<?php endwhile;?>
<thead>
<tr>
<th> Total </th>
<th>
<?php
echo $sum;
?>
</th>
</tr>
</thead>
</table>

JQuery multiple variables sent in url

I have searched for hours now to find out how I could do this, but unfortunately all to no avail.
I am trying to send entered information so it can run through MySQL and obtain the information, then echo it in table on screen.
The issue (as far as I can tell) must be with my JQuery code:
$("#btnCheckNoteIDs").click(function(){
var noteUser = $("#noteUser").val();
var noteDate = $("#noteDate").val();
$("#LoadNoteIDs").load('check_noteIDs.php?noteDate='+noteDate + "&noteUser="+noteUser);
});
My php code is as follows:
$result = mysqli_query($con,"
SELECT ID, ClientID, Note, ToDoDate, CaseID
FROM ToDoNotes
WHERE ToDoStatus='0' and Deleted='0' and `ToDoDate`='".$_GET['noteIDsDate']."' and User='".$_GET['noteIDsDate']."'");
while($row = mysqli_fetch_array($result))
{
$ID = $row['ID'];
$ClientID = $row['ClientID'];
$Note = $row['Note'];
$ToDoDate = $row['ToDoDate'];
$CaseID = $row['CaseID'];
}
?>
<table class="table table-striped">
<thead>
<tr>
<th>Note ID</th>
<th>Client ID</th>
<th>Case ID</th>
<th>Note</th>
<th>To Do Date</th>
</tr>
</thead>
<tbody>
<tr>
<td><? echo $noteID; ?></td>
<td><? echo $ClientID; ?></td>
<td><? echo $CaseID; ?></td>
<td><? echo $Note; ?></td>
<td><? echo $ToDoDate; ?></td>
</tr>
</tbody>
</table>
Can anyone here offer any assistance please? Any help will be greatly appreciated!
Thanks!
Suppose you have form.php like below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form method="post" id="btnCheckNoteIDs">
<label> User</label>
<input type="text" name="user" id="noteUser"><br>
<label>Date</label>
<input type="date" name="date" id="noteDate"><br>
<input type="submit" value="submit">
</form>
<br>
<div id="LoadNoteIDs"></div>
</body>
</html>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script>
$(document ).ready(function() { //make sure document is ready
$('#btnCheckNoteIDs').submit(function(e){
e.preventDefault();//to prevent default behaviour
var noteUser = $("#noteUser").val();
var noteDate = $("#noteDate").val();
if(noteUser==undefined){
alert('No noteuser');
return false;
}else if(noteDate==undefined){
alert('no note date');
return false;//stop sending
}
//to convert %2F, use decodeURIComponent
var param= 'noteDate='+decodeURIComponent(noteDate) + '&noteUser='+noteUser;
$.ajax({
url: "check_noteIDs.php",
data: param,
type: "post",
success: function(data){
$('#LoadNoteIDs').html(data);
}
});
});
});
</script>
in check_noteIDs.php which must be in the same folder where you put the form.php
require_once "dbconfig.php";
$user= isset($_REQUEST['noteUser'])? $_REQUEST['noteUser']:'';
$date = isset($_REQUEST['noteDate'])? date('Y-m-d', strototime($_REQUEST['noteDate'])):'';
//You can validate here.
$result = mysqli_query($con," SELECT ID, ClientID, Note,
ToDoDate, CaseID
FROM `ToDoNotes`
WHERE `ToDoStatus`='0' AND `Deleted`='0'
AND `ToDoDate`='$date'
AND `User`='$user'");
$row = mysqli_fetch_assoc($result);
<table class="table table-striped">
<thead>
<tr>
<th>Note ID</th>
<th>Client ID</th>
<th>Case ID</th>
<th>Note</th>
<th>To Do Date</th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $row['ID']; ?></td>
<td><?php echo $row['ClientID']; ?></td>
<td><?php echo $row['CaseID']; ?></td>
<td><?php echo $row['Note']; ?></td>
<td><?php echo $row['ToDoDate']; ?></td>
</tr>
</tbody>
</table>
<?php
mysqli_free_result($result);
mysqli_close($con);
?>
I think your issue is the submit button in your form, submits the form before the script executes. If that's the case, you need to update your script as below:
$("#btnCheckNoteIDs").click(function(event){
event.preventDefault();
var noteUser = $("#noteUser").val();
var noteDate = $("#noteDate").val();
$("#LoadNoteIDs").load('check_noteIDs.php?noteDate='+noteDate + "&noteUser="+noteUser);
});

Use Select option as search with dynamic fields

I am making a site linked with a database. It sorts transactions for budgeting reasons. For the store search section, I have a select drop down menu. I have linked up the data so that the drop down only shows stores that are in the database and automatically adds them as they change dynamically.
My issue is that I need a way to actually use the select options as search terms. Here is the initial page.
<!DOCTYPE html>
<html>
<head>
<title>Output 1</title>
</head>
<body>
<h1>Required Output 1</h1>
<h2>Transaction Search</h2>
<form action="output1out.php" method="get">
Search Store:<br/>
<input type="text" name="StoreName">
<br/>
<input name="Add Merchant" type="submit" value="Search">
</form>
<?php
require_once 'login.php';
$connection = mysqli_connect($db_hostname, $db_username,$db_password, $db_database);
if(mysqli_connect_error()){
die("Database Connection Failed: ".mysqli_connect_error()." (".mysqli_connect_errno().")");
};
$query = "SELECT * from PURCHASE";
//echo $query;
$result = mysqli_query($connection,$query);
if(!$result) {
die("Database Query Failed!");
};
$distinct = "SELECT DISTINCT StoreName FROM PURCHASE";
$distinctResult = mysqli_query($connection,$distinct);
if(!$result) {
die("Database Query Failed!");
};
echo '<select name="search_string" />'."\n";
while ($row = mysqli_fetch_assoc($distinctResult)){
echo '<option value="'.$row["StoreID"].'">';
echo $row["StoreName"];
echo '</option>'."\n";
};
echo '</select>'."\n";
mysqli_free_result($result);
mysqli_close($connection);
?>
Here is the output page.
<?php
$transaction = $_REQUEST["StoreName"];
require_once 'login.php';
$connection = mysqli_connect($db_hostname, $db_username,$db_password, $db_database);
$sql = "SELECT * FROM PURCHASE WHERE StoreName LIKE '%".$transaction."%'";
$result = $connection->query($sql);
?>
Purchases Made From <?php echo $transaction ?>
<table border="2" style="width:100%">
<tr>
<th width="15%">Item Name</th>
<th width="15%">Item Price</th>
<th width="15%">Purchase Time</th>
<th width="15%">Purchase Date</th>
<th width="15%">Category</th>
<th width="15%">Rating</th>
</tr>
</table>
<?php
if($result->num_rows > 0){
// output data of each row
while($rows = $result->fetch_assoc()){ ?>
<table border="2" style="width:100%">
<tr>
<td width="15%"><?php echo $rows['ItemName']; ?></td>
<td width="15%"><?php echo $rows['ItemPrice']; ?></td>
<td width="15%"><?php echo $rows['PurchaseTime']; ?></td>
<td width="15%"><?php echo $rows['PurchaseDate']; ?></td>
<td width="15%"><?php echo $rows['Category']; ?></td>
<td width="15%"><?php echo $rows['Rating']; ?></td>
</tr>
<?php
}
}
?>
I can get regular typing search to work but I can't think of a way to search using the same method. Is it possible?

Categories