I have a database with many records (major columns are Date, Company Names, Closing Price. What i want to achieve is to use php to display all unique company names in the first column, most recent price in the 2nd (using date), Highest Price of all unique companies in database in the 3rd column and lowest price of all unique companies in the database. Please, how can i achieve this?
$query = "SELECT date, company, MIN(close), MAX (Close) FROM pricelist GROUP BY company";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
for ($i=0;$i<$num_rows;$i++){
$id = mysql_result($result,$i,"id");
$date = mysql_result($result,$i,"date");
$company = mysql_result($result,$i,"company");
$close = mysql_result($result,$i,"close");
echo "<tr bgcolor=\"#d7dde3\"><td align=right class=no_text>".$company."</td><td align=right class=norm_text>".number_format($close, 2, '.', ',')." </td><td align=right class=norm_text>".$date." </td></tr>";
}
Here is what i am trying to achieve:
Company Name Year High Date Year Low Date
Google $20 02/17/2014 $10 05/13/2014
Apple $40 01/22/2014 $34 04/05/2014
Select all records by date, then use php arrays, asort() - low->high, arsort() - high->low.
Find more about php array here: PHP Array Sorting
You can try it, but not tested
SELECT DISTINCT company, price, MAX (price),MIN(price) FROM pricelist
ORDER BY date DESC
Related
I'm just starting to learn php. Everything I've researched references an array for sorting but I can't figure out how to make that work in this situation since one of my fields is constantly changing so I can't create a fixed array. Remember, I'm a noob so please explain in detail.
I would like to sort based on two fields how the results are displayed.
The first field on which to sort should be based on "SortOrder" as it correlates to the "TaskSubType" field (Displayed as Ticket Type on forms. TaskSubType has the following values assigned and would work in an array:
MSP = 1
DEDICATED = 2
REMOTE SUPPORT = 3
EXPEDITED = 4
EXPEDITED - $25 = 4
STANDARD = 5
STANDARD - $25 = 5
So if the Ticket Type (TaskSubType) was selected as "Dedicated" then it would be sorted as "2" and if "Standard - $25" was selected as the Ticket Type (TaskSubType) then it would be sorted as "5".
The second field on which I want to sort is the Ticket Number (TicketNumber) field. The value in this field is constantly changing since we have new tickets created every day so I don't know how to sort on this field with an array.
Main Goal: I want to sort the results by Ticket Type according to the numeric value we have assigned to each type which is our repair priority and then sort within all the "Dedicated" or "Standard" to work each ticket in that group in the order it was created (each new ticket counts up by one).
The code below is what I have working up to this point and the weblink below shows how my results are currently displaying:
Webpage where results are shown:
https://fireytech.com/FireytechDatabase/hello.php
Code:
<?php
require '../../db_php/dbconnection.php';
$sql = "SELECT * FROM
Tickets
Left JOIN
Clients
ON Tickets.CustomerNumber=Clients.CustomerNumber
JOIN Contacts
ON Contacts.ContactID=Clients.CustomerNumber
JOIN Equipment
ON Equipment.ContactID=Clients.CustomerNumber
WHERE Equipment.PRINT = '-1' AND Contacts.DispatchContact = '-1' AND TicketStatus = 'Active' AND NOT TicketSubStatus = 'CUSTOMER PICKUP' AND NOT TaskSubType = 'ON-SITE'
";
$result = $conn->query($sql);
echo"<table border='1'>";
echo "<tr><td>Ticket Type</td><td>Ticket Number</td><td>Date Received</td><td>Last Edited</td><td>Last Name</td><td>Followup By</td><td>Sub Status</td><td>Repair Type</td><tr>";
if ($result->num_rows > 0){
while($row = $result->fetch_assoc() ){
$dr= date("m/d/Y", strtotime($row['DateReceived']));
$dl= date("m/d/Y", strtotime($row['DateLastEdited']));
echo "<tr><td>{$row['TaskSubType']}</td><td>{$row['TicketNumber']}</td><td>{$dr}</td><td>{$dl}</td><td>{$row['ContactLast']}</td><td>{$row['FollowupBy']}</td><td>{$row['TicketSubStatus']}</td><td>{$row['ItemType']}</td></tr>";
}
} else {
echo "0 records";
}
echo"</table>";
$conn->close();
?>
Murosadatul gave me the clarity I needed. I had tried the ORDER BY command but didn't realize I need to put it at the end of my SQL query. Below in bold is where I placed it in my code so it worked if anyone else runs into the same problem:
$sql = "SELECT * FROM
Tickets
Left JOIN
Clients
ON Tickets.CustomerNumber=Clients.CustomerNumber
JOIN Contacts
ON Contacts.ContactID=Clients.CustomerNumber
JOIN Equipment
ON Equipment.ContactID=Clients.CustomerNumber
WHERE Equipment.PRINT = '-1' AND Contacts.DispatchContact = '-1' AND TicketStatus = 'Active' AND NOT TicketSubStatus = 'CUSTOMER PICKUP' AND NOT TaskSubType = 'ON-SITE'
->->->->->->-> ORDER BY SortOrder, TicketNumber
"
;
$result = $conn->query($sql);
I have two tables one having employee name, employee id and another table tblleaves having empid,Leave_Date, fromDate, toDate, Description.
If user choose one day leave it stores the date value to Leave_Date and if user choose multiple days it store value of from date and to date.
Now I want the monthly report of employees. In this page I want an employee name, Leave Days and Leave Dates. I tried codes but I got employee name repeatedly because they apply many leaves in that month i want to display employee name one time.
<?php
if(isset($_POST['apply'])){
$ym=$_POST['month'];
list($Year, $Month) = explode("-", "$ym", 2);
$sql = "SELECT distinct tblleaves.id as lid,tblemployees.FirstName,tblemployees.LastName,tblemployees.EmpId,
tblemployees.id,tblleaves.LeaveType,tblleaves.PostingDate,
tblleaves.Leave_Date from tblleaves join tblemployees on tblleaves.empid=tblemployees.id
WHERE YEAR(Leave_Date) = 2019 AND MONTH(Leave_Date) = 6";
echo $sql;
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $result)
{ ?>
<tr>
<td> <?php echo htmlentities($cnt);?></td>
<td><?php echo htmlentities($result->FirstName);?> <?php echo htmlentities($result->LastName);?></td>
<td><?php ?></td>
<td><?php $result->Leave_Date?></td>
<?php $cnt++;}}}?>
I want employee monthly leave report
employee name Leave Days Leave Dates
KrishnanR 3 12-06-2019, 13-06-2019, 14-06-2019
Really that sort of formatting should be done in the report itself by having a band that occurs once per emplyee and shows the name and then within band show all the records for that employee.
However you can get a dataset containing the example result you posted by using the MySQL function GROUP_CONCAT().
The following code will give you three columns, FirstName, LastName and leave_dates with one row per employee. The leave_date column will contain all their tblleaves.Leave_Date values, separated by a comma and a space (or whatever appears after the key word SEPARATOR.
You won't need the DISTINCT
SELECT
tblemployees.FirstName,
tblemployees.LastName,
count(tblleaves.empid) as Leave_Days,
GROUP_CONCAT( tblleaves.Leave_Date SEPARATOR ', ' ) AS leave_dates
FROM
tblleaves
JOIN tblemployees
ON tblleaves.empid = tblemployees.id
WHERE YEAR(Leave_Date) = 2019
AND MONTH(Leave_Date) = 6
GROUP BY tblemployees.EmpId
I have a table with columns name and amount, i want to query data that sum(amount) upto lets say 1000 in each group, in cases where a row value is greater than 1000 it can be still be displayed in its own group. i have tried this using a php loop of sum that range between 500 to 1000 but this way produces so many groups that i wish could be a voided. is there any way that we can do this in a single mysql query. regards
this is the way i crooked my way!
//this query helped me in maneuvering in provision of limits each time
$totalLines=mysql_query("select COUNT(*) as totalRows from chasis where chasis.BL_No =xxxx order by chasis.BL_No ")or die(mysql_error());
$fetch_totalLines=mysql_fetch_array($totalLines);
$found_rows=$fetch_totalLines['totalRows'];
$total=0;
$Toplimit=0;
$z=0;
a:
if($Toplimit>0){
$Toplimit=$Toplimit;
//$found_rows=$found_rows-$Toplimit;
$total=0;
}
$query=mysql_query("select * from chasis where chasis.BL_No =xxxx order by chasis.duty_amount limit ".$Toplimit.",".$found_rows." ")or die(mysql_error());
$i=1;
while($row=mysql_fetch_array($query)){
$total=round($row['duty_amount'],0)+$total;
echo'<tr>
<td>'.$i.'</td>
<td>'.$row['BL_No'].'</td>
<td>'. mb_substr($row["make"], 0, 1,"UTF8")."-";
echo $row["model"];
echo'</td>
<td>'.$row['chasisNo'].'</td>
<td>'.$row['cc'].'</td>
<td>'.date("Y F", strtotime($row['year'])).'</td>
<td>'.$row['EntryNumber'].'</td>
<td>'.round($row['duty_amount'],0).'</td>
<td> </td>
</tr>';
if($total<=1000 and $total>=500 ){
echo"<td colspan='8' align='right'><b>Duty Cheque for ".$i." units</b></td>
<td><b>".$total."</b></td>
";
$Toplimit=$Toplimit+$i;
$z=$z+$i;
goto a;
}
$i++;
}
I have decided to show everything that i did may to reflect the usage of goTo statement to hold the column id
I know this is a poor way to handle this but am really stuck.
Could you please try this way
select * from chasis where chasis.BL_No =xxxx AND chasis.duty_amount>=500 AND chasis.duty_amount<=1000 order by chasis.duty_amount
i have the following table with values from a sql query:
now depending on the hour of the day, i want to be able to change the values.
for example, its late in the afternoon, i choose the option 3 dagen EUR 20.00. Since right now this day is already almost over, i should pay a smaller amount for 1 dag (example EUR 4), and then the price for 2 dagen EUR 14.00, so at this hour of the day the box 3 dagen should show EUR 18.00
So i know how to get the current hour, but how can i change my query to reflect this?
This is the query i used to get this table:
<?php
echo "<h2>".$lang['pagina3_dagen']."</h2>";
$number=="0";
echo "<table class='prijs'>";
echo "<tr>";
$query="SELECT * FROM $tabel WHERE fietstype='$fietskeuze'";
$result=mysql_query($query) or die ("Ophalen prijzen mislukt: ".mysql_error());
while ($row=mysql_fetch_array($result)) {
$days=$row[days];
$price=$row[price];
if ($days=="1") $writeday=$lang['pagina3_1dag'];
if ($days >="2") $writeday=$lang['pagina3_meerderedagen'];
echo "<td class='prijs'><h2><a href='framemaat.php?lang=".$_SESSION['lang']."&naam=".$naam."&postcodehuisnummer=".$postcodehuisnummer."&fietskeuze=".$fietskeuze."&opties=".$opties."&optieid=".$optieid."&days=".$days."'>".$days." ".$writeday."<br>EUR ".$price."</a><br>";
$number++;
if ($number=="5") {echo "<tr>"; $number="0";}
}
echo "</tr>";
echo "</table>";
?>
i was thinking in pseudo-like code something like this:
$currenthour = date("H", time());
if (($currenthour >="13") && ($currenthour <"15"))
{
$pricedag1=($pricedag1-3eurodiscount);
price in table result for 3 dagen=($pricedag1+$priceofdag2)
}
but how to get the price of the previous day? so the second to last value coming from the query?
I'm not entirely sure I understand the details of your table, but here's a shot:
Why not have a separate table that holds discounts for your products (dagens?) ? This way, you can query your products and join it against the discount table.
// you can decide the data type
CREATE TABLE Discounts (discount_id, product_id, start, end, discount);
then you could left join with your product table
SELECT p.*, d.discount
FROM products p
LEFT JOIN discounts d ON d.product_id = p.product_id
AND start <= ? AND end >= ?;
So after you've received your result set, you can check whether discount is empty or not. If it's not, apply the necessary discount.
if (!empty($row['discount']) {
$price = $price - $row['discount'];
}
Of course, you could take it a step further and determine types of discounts - percentage off, dollar off, etc.
I'm working on a job at the minute where all the products within the store need to be brought in and show how many orders have been put through in-between that time period which was easy to do, but it also in the same table needs to split the quantity of the orders of that product into the separate months that it was ordered in, is there any way to expand the data from one cell that's been group and do a count on it and then separate it into sub months?
$this->obDb->query ="SELECT vSku,fOrdertime,iOrderStatus,fPrice,SUM(iQty) as iQty,tShortDescription,fBuyprice as totalBuyPrice, vTitle FROM ".ORDERS.",".ORDERPRODUCTS." WHERE iOrderid_FK=iOrderid_PK AND ";
$this->obDb->query.=$statusquery;
if(isset($this->request['start_date']) & $this->request['start_date']>0){
$this->obDb->query.=" AND tmOrderDate >='".$this->request['start_date']."'";
}else{
$this->err=1;
$this->errMsg=INVALID_START_DATE."<br>";
}
if(isset($this->request['end_date']) & $this->request['end_date']>0){
$this->obDb->query.=" AND tmOrderDate <='".$this->request['end_date']."' GROUP BY vTitle";
}else{
$this->err=1;
$this->errMsg.=INVALID_END_DATE;
}
if($this->err==0){
$queryRs = $this->obDb->fetchQuery();
$recordCount=$this->obDb->record_count;
if($recordCount>0){
$this->ObTpl->set_var("TPL_VAR_FROMDATE", $this->libFunc->dateFormat2($this->request['start_date']));
$this->ObTpl->set_var("TPL_VAR_TODATE", $this->libFunc->dateFormat2($this->request['end_date']));
for($i=0;$i<$recordCount;$i++)
{
$this->ObTpl->set_var("TPL_VAR_STATUS","Incomplete");
if($queryRs[$i]->iOrderStatus==1){
$this->ObTpl->set_var("TPL_VAR_STATUS","Complete");
}
If I understand what you're asking you could try
SELECT datecol, COUNT(id)
FROM your_table
WHERE datecol BETWEEN date1 AND date2
GROUP BY productId, YEAR(datecol), MONTH(datecol)
ORDER BY datecol