SQL pulling data based on date - php

I have a database full of store information and personal transactions. I have two webpages. One takes user input for the store name and runs a query pulling all transaction info for that store. I have another page almost identical that takes input for a start date and an end date and then runs a query for transactions between that date. The one for the store name works perfectly, but the one for the date doesn't display anything. I am still learning html/php/sql but I know exactly how the first page works so I cannot see why the same doesn't work for the second. If someone could help me, I'd appreciate it.
Here is my first page for the store name search that works.
<?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['PurchaseCategory']; ?></td>
<td width="15%"><?php echo $rows['Rating']; ?></td>
</tr>
<?php
}
}
?>
And here is the page for the date search that returns no data.
<?php
$startDate = $_REQUEST["StartDate"];
$endDate = $_REQUEST["EndDate"];
require_once 'login.php';
$connection = mysqli_connect(
$db_hostname, $db_username,
$db_password, $db_database);
$sql = "SELECT * FROM PURCHASE WHERE PurchaseDate BETWEEN '%".$startDate."%' and '%".$endDate."%'";
$result = $connection->query($sql);
?>
Purchases Made Between <?php echo $startDate ?> and <?php echo $endDate ?>
<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['PurchaseCategory']; ?></td>
<td width="15%"><?php echo $rows['Rating']; ?></td>
</tr>
<?php
}
}
?>
Obviously the initial search pages that link to both of these output pages differ a bit more but I can confirm that the date output page is receiving the correct dates from the search page.
EDIT: Here is the search page for the date.
<!DOCTYPE html>
<html>
<head>
<title>Output 2</title>
</head>
<body>
<h1>Required Output 2</h1>
<h2>Transaction Search By Date</h2>
<br/>
<br/>
<form action="outputout2.php" method="get">
Start Date: <input type="date" name="StartDate">
End Date: <input type="date" name="EndDate">
<input name="Add Merchant" type="submit" value="Search">
</form>;
</body>
</html>

This sort of problem is usually the result of misformatted dates.
Your query, if I'm reading it right, says this when you've finished assembling it in php and sent it to the SQL server:
SELECT *
FROM PURCHASE --wrong!
WHERE PurchaseDate BETWEEN '%5/1/2016%' and '%5/8/2016%'
This is not going to work.
For one thing, the % signs only work with the LIKE operator, not on equality and inequality operators.
For another thing, different makes and models of database server software use differently formatted date strings. MySQL and SQL Server will work fine with string formats like 2016-05-01. But you have to look up the appropriate ways of doing this for the kind of SQL software product you are using. This kind of stuff is not very vendor-portable.
Third: your PurchaseDate column in your table needs to have a date-like datatype for this kind of thing to work.
Fourth: if your PurchaseDate items are timestamps -- that is, if that have both dates and times -- you can't reliably use the BETWEEN operator. Here's why: Suppose you have a value of 2016-05-08 11:50:00 When you compare that to an end date 2016-05-08, it lies beyond the end date. So, what you really need is this:
WHERE PurchaseDate >= '2016-05-01'
AND PurchaseDate < '2016-05-09' -- the day AFTER your end date
That construct performs the same as BETWEEN and doesn't screw up the last days' data.
Edit so it's MySQL you're using.
Workbench is a client program. So is PHP. The server is MySQL. When you do an operation like
DateColumn < 'string constant'
MySQL implicitly converts the string constant to a date. If the format of the string constant is close enough to ISO 8601 for the server to figure out what it means, it will convert it. 2016-12-13 is exactly right. 2016-5-31 is close enough for MySQL, and so is 2016-5-5. 2016/12/31 doesn't work. Neither does 5/5/16.
Germane to your question is this: MySQL cannot convert %2016-5-5% (with the percent signs) to a date.
When MySQL can't convert a date, it comes up with NULL. Comparisons with NULL values are weird. And, in the immortal words of Hunter S. Thompson, "when the going gets weird, the weird turn pro". NULL weirdness is probably the root cause of your empty result set in the query you showed.

Related

when selecting from a php populated dropdown use the desired data and populate an html table with more php depending on which data was selected

Hello and thanks for coming.
So I have the Category table with "n" values on it, and I have the table Price with "n" duplicated idCategorys (foreign Key) in it.
What I want to do is when selecting a Category from a dropdown menu a Html Table gets populated with all the prices with the Category i've chosen.
So far I've managed to get a dropdown select menu populated with php as follows:
<select name="categorias" required id="categorias" >
<?php $render = mysqli_query($con,"SELECT idCategoria FROM neomixlt_desarrollo.Categorias");
while($row1 = mysqli_fetch_array($render)) {
echo "<option value='" . $row1['idCategoria'] . "'>" . $row1['idCategoria'] ."</option>";
}
?>
</select>
And a table populated as follows
<table width="957" border="2" cellspacing="0">
<tr>
<th width="98" style="text-align: center">Categoria</th>
<th width="99" style="text-align: center">Articulo</th>
<th width="348" style="text-align: center">Precio a Domicilio(bs.)</th>
<th width="348" style="text-align: center">Precio en Planta(bs.)</th>
<th width="40" style="text-align: center"></th>
</tr>
<?php $render = mysqli_query($con,"SELECT * FROM neomixlt_desarrollo.precios_articulo WHERE idCategoria=$link ORDER BY idCategoria DESC ") or die(mysql_error()); ?>
<?php while($row1 = mysqli_fetch_array($render)):; ?>
<tr>
<td style="text-align: center"><?php echo $row1['idCategoria']; ?></td
><td style="text-align: center"><?php echo $row1['idArticulo']; ?></td>
<td style="text-align: center"><?php echo $row1['precio_domi']; ?></td>
<td style="text-align: center"><?php echo $row1['precio_plant']; ?></td>
<td style="text-align: center"><?php echo "<a href=editar_precios.php?pid=$row1[idArticulo]&cid=$row1[idCategoria]&precio_domi=$row1[precio_domi]&precio_plant=$row1[precio_plant]>editar</a>" ?></td>
</tr>
<?php endwhile; ?>
</table>
But they are not linked and I have not much idea on how to do this. im restricted to use php and html only and all similar examples I've found are using javascript or ajax, any idea? thanks in advance!
w/o JavaScript, JQuery, Angular, etc. available, you'll need to submit every time.
So load the page up in its original state, the user will choose their category. Now w/o JS available to go run updates nicely for you, you'll need to submit a form back to the server, then on the server side, get the POST category, and build the desired HTML and send that to the browser to view. This will have to be done every time they change categories.

Extra rows in dynamic table populated from SQL Server 2012 and PHP

I am generating a dynamic table, from the databasw (SQL Server 2012) using php. Using the code pasted below :
<table class="table table-bordered" id="tb">
<tr style="BACKGROUND-COLOR: DarkGrey ">
<th colspan="4" style="text-align:Center;">Objectives and Targets </th>
</tr>
<tr class="tr-header">
<th>Objectives / Measures</th>
<th colspan="2">Targets / Achievements / Timelines</th>
<th style="text-align:Center;width:1%;" rowspan="2">Weightage %</th>
</tr>
<tr>
<th> </th>
<th> </th>
<th style="width:10%;"> Date </th>
</tr>
<tbody>
<?PHP
$myquery=" select replace(Objectives, '||<==', '') as Objectives, replace(Targets, '==', '') as Targets, replace(Weightage, '==', '') as Weightage, Corporate_Objective, Corporate_Objective_Weightage from Appraisal_Objectives WHERE Serial_Number='$Serial_Number' ORDER BY Row_Number asc";
$fetched=sqlsrv_query($conn,$myquery) ;
if( $fetched === false ) { die( print_r( sqlsrv_errors(), true ));}
while($res=sqlsrv_fetch_array($fetched,SQLSRV_FETCH_ASSOC))
{
$Corporate_Objective=$res['Corporate_Objective'];
$Weightage=$res['Weightage'];
$Objectives=$res['Objectives'];
$Targets=$res['Targets'];
$Corporate_Objective_Weightage=$res['Corporate_Objective_Weightage'];
echo "<tr><td>".$Corporate_Objective."</td>";
echo "<td></td>";
echo "<td></td>";
echo "<td><b>".$Corporate_Objective_Weightage."</b></td></tr>";
echo "<tr><td>".$Objectives."</td>";
echo "<td>".$Targets."</td>";
echo "<td></td>";
echo "<td>".$Weightage."</td></tr>";
}
?>
</tbody>
</table>
Issue
The output is creating many unwanted, blank rows inbetween each row! I haven't added any <br/> or and extra row in the code. Also, the rows in the databse do not have any spaces.
Where could I have gone wrong. Appreciate any help/suggestion. Thanks in advance.
ScreenShot of the dynamic table output
I changed my SQL Query and used COALESCE. The code is as below :
select Targets,target_date,ROW_NUMBER,
COALESCE(Corporate_Objective,Objectives) AS Objectives,
COALESCE(Corporate_Objective_Weightage,Weightage) AS Weightage
FROM Appraisal_Objectives WHERE Serial_Number like '%1153';
This removed all the spaces in the table :

PHP MySQL table mouse-over event to display information stored in MySQL (using Dreamweaver)

I have a database of players and their info in mysql. I have created a table in dreamweaver displaying all the players and their info. I want to display a player profile (which is stored in mysql) seperate from this table and want this information to change when the mouse is over a player in the table.
Is this possible and how do i go about it? Any help or links to tutorials will be greatly received!
I have a Screenshot of my page but am unable to post due to reputation if anyone wants to visualise my idea maybe i could send it them?
<div class="playerInfoContainer">
<table width="95%" border="0" cellpadding="3">
<caption>
Player Profile
</caption>
<tr>
<td><?php echo $row_Recordset1['PlayerProfile']; ?></td>
</tr>
</table>
</div>
</div>
<div class="squadListContainer">
<div class="DatabaseContainer">
<table width="95%" border="0" cellpadding="3">
<caption>
Bedlinog Veterans Squad
</caption>
<tr>
<th scope="col">Player Name</th>
<th scope="col">Position</th>
<th scope="col">Date of Birth</th>
<th scope="col">Points Tally</th>
<th scope="col">Man of the Matches</th>
</tr>
<?php do { ?>
<tr>
<td width="130"><?php echo $row_Recordset1['PlayerName']; ?></td>
<td width="100"><?php echo $row_Recordset1['Position']; ?></td>
<td width="100"><?php echo $row_Recordset1['DateOfBirth']; ?></td>
<td width="100"><?php echo $row_Recordset1['PointsTally']; ?></td>
<td width="100"><?php echo $row_Recordset1['MOM']; ?></td>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
</table>
</div>
Firstly, pre-build all of the displayed mouse-over data into separate XML/JSON files. That way there's no load on a database to display 15 items at once when someone goes nuts with their cursor.
Secondly, use jquery to display a mouseover event to populate a div on the page with the separate HTML files.
As long as your jquery is correct and your css skills are up to snuff, the details will change as required and maintain the correct look/feel as it goes from one 'team/squad' to the next.

Can we make results of MySQL select query editable and sortable?

I have a select query which pulls up data from a table and displays it accordingly
$display_query= "select * from customer WHERE abc_mailing_list = '$abc' AND def_mailing_list ='$def' AND ghi_mailing_list = '$ghi' AND position_category IN($var) AND country_code='$country_cat' ORDER BY state";
$display_result=mysqli_query($dbc2,$display_query);
<table width = "100%"border="1" style="border-collapse: collapse;">
<tr style="background-color: #51626F; color: #FFFFFF;">
<th> S.No</th>
<th> First Name</th>
<th>Last Name</th>
<th>Position Category</th>
<th>State</th>
<th>Country</th>
<th>Title</th>
<th>Agency</th>
<th>Department</th>
</tr>
<?php
$colour2 = "transparent";
$colour1 = "#B1B0A7";
$count = 0;
$row_count = 0;
while($row=mysqli_fetch_assoc($display_result)){
$rowcolor = ($row_count % 2) ? $colour1 : $colour2;
$count++;
?>
<tr style="background: <? echo $rowcolor; ?>;">
<td width="10%" height="20"><? echo $count; ?></td>
<td width="10%" height="20"><? echo $row['first_name']; ?></td>
<td width="10%" height="20"><? echo $row['last_name']; ?></td>
<td width="10%" height="20"><? echo $row['position_category']; ?></td>
<td width="10%" height="20"><? echo $row['state']; ?></td>
<td width="10%" height="20"><? echo $row['country_code']; ?></td>
<td width="10%" height="20"><? echo $row['title']; ?></td>
<td width="10%" height="20"><? echo $row['agency']; ?></td>
<td width="10%" height="20"><? echo $row['department']; ?></td>
</tr>
<?
$row_count++;
}
?>
My question is I want to make everything editable so that if the user finds some mistake in the returned results, he should have the option to edit then and there and save it, so that it can be saved in the database. Is there any plugin for this? I'm sorry if this is a trivial question, I'm new to PHP. Thanks
The edit part would take some work, but you could use DataTables (a JQuery plugin) to handle the sorting, searching etc..
DataTables (table plug-in for jQuery)
www.datatables.net
You are missing some understanding about how this works. What you do now is show the data in a web page. You need to implement a mechanism to update the database back, this is not going to happen instantly, you need to show the data in an editable format like a textbox and than let the user change it and click an update button for example when he is done. then you need to respond to a click on that button, take the edited data from the textbox and update the right location in the database. that is simply put and can be done in many different ways. start doing something and post some code so we could help :)
instead of
'<td width="10%" height="20"><? echo $count; ?></td>'
you should have this column be a unique auto-incrementing number from the database, so each row can be identified. from there, you can use forms(either checkboxes to select which colums need to be edited, or text inputs that can be edited on each column). if you choose to use checkboxes and a 'edit' button, have a hidden input with the unique id attached. Then check if
(isset($_POST['id']) && isset($_POST['firstName']))
{
$firstName = sanitizeStrin($_POST['firstName']);
$id = sanitizeString($_POST['id']);
mysql_query( "UPDATE table SET first_name = '$firstName' WHERE uniqueID='$id'" );
}
.. ect to see which column in which row needs to be updated. A lot of code is needed to check every column, but you get the idea. Hope this helps.

SELECTING in two tables...

I have two tables that I want to use for viewing my reports which I can get after inputting a date.
Here are my tables: for customers - customer_date, lastname, firstname
for services - room_number, date_in, date_out
Here is my code now : it seems that it can't get any rows from my table
<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db('irm',$conn);
if(isset($_GET['Submit'])){
$customer_date = $_GET['customer_date'];
}
?>
<form method="get">
<table width="252" border="0">
<tr>
<td width="98">Choose Date:</td>
<td width="144"><label>
<input onclick="ds_sh(this);" name="customer_date" id="customer_date" readonly="readonly" style="cursor: text" />
</label></td>
</tr>
<tr>
<td align="right"><input type="submit" value="Submit" /></a></td>
<td></td>
</tr>
</table>
</form>
<form>
<?php
$tryshow = "SELECT * FROM customers,services WHERE customer_date = '$customer_date' ";
$result = #mysql_query($tryshow,$conn)
or die("cannot view error query");
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print...";
}
while($row=mysql_fetch_assoc($result)){
?>
<table width="700" border="0">
<tr>
<td width="100">Customer Date:</td>
<td width="100">Last Name</td>
<td width="100">First Name</td>
<td width="100">Room Number</td>
<td width="100">Date In</td>
<td width="100">Date Out</td>
</tr>
<tr>
<td><?php echo $row["customer_date"]; ?></td>
<td><?php echo $row['lastname']; ?></td>
<td><?php echo $row['firstname']; ?></td>
<td><?php echo $row['room_number']; ?></td>
<td><?php echo $row['date_in']; ?></td>
<td><?php echo $row['date_out']; ?></td>
</tr>
</table>
<?php }?>
</form>
With this I can get a report of any customer who checks in on that date.
I need some advice. Hope you can answer me soon.
You don't appear to have any fields in common between the two tables. How do you store fact that customer A was in room B on date C? To do an SQL join, the tables being joined have to have at least one field in common.
As well, instead of just saying die("cannot view error query"), which is utterly useless for debugging purposes, try doing die(mysql_error(), which will give you the exact reason the query failed.
As well, if the query DOES work, then you're outputting an entire HTML table for each row found. You should have the table headers and footers data OUTSIDE of the fetch loop.
You need to relate the two tables with a JOIN. Based on the information given, customers.customer_date to services.date_in seems to be the most likely candidate. This assumes that the date columns hold only a date and not a date/time.
Also notice that I'm not using select * in my query and neither should you. ;-)
SELECT c.customer_date, c.lastname, c.firstname,
s.room_number, s.date_in, s.date_out
FROM customers c
INNER JOIN services s
ON c.customer_date = s.date_in
WHERE c.customer_date = '$customer_date'
When your making query to database make sure your date format is yyyy-mm-dd
Mysql understand date in this format only so that you have to compare the date format in this format only.
your $customer_date should be in the yyyy-mm-dd format
As an aside, I'd change customer_date to something more meaningful such as "date_in." (It's a good thing when the names are predictable!) You don't need to specify that it's the customer since it's in the customer table already.

Categories