Sorting PHP Results of a query on two fields - php

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);

Related

How to create an alphabetized drop down menu in PHP

I'm trying to re-write this code so that the drop down menu is alphabetized:
$activeProjectDropdown.="<option value=''>Select Project</option>";
$getInfo = "SELECT id, customer, job_name, haul_info
FROM dispatch_jobs
WHERE (:mydate BETWEEN delivery_date AND delivery_date_end)
ORDER BY customer, job_name";
$result=DB::run($getInfo, ['mydate' => $myDate]);
while($row=$result->fetch(PDO::FETCH_BOTH)) {
if(!empty($row['haul_info'])) {
$haulinfo = "($row[haul_info])";
}else{
$haulinfo = "";
}
if($checkit == $row['id']){
$woot = 'selected=selected';
}else{
$woot = '';
}
$customerName = pdo_getName('name', 'customer', "$row[customer]");
$activeProjectDropdown.="<option value='$row[customer]|$row[id]' $woot>$customerName $haulinfo</option>\n";
}
In this code the query returns some rows from the database where customer is a numeric code which isn't in any kind of alphabetical order. Further down in the code a function called pdo_getName is called which takes a column of name table of customer and the id from $row['customer'] and queries the database, returning the stringified name of the customer. Because the name isn't being retrieved until later on down the loop I'm having trouble figuring out a way that I can alphabetize the $activeProjectDropdown. I've tried putting the $customerName and drop down code into an associative array, then sort that by $customerName and concat everything into a string, but that didn't work because there are duplicate keys. Down that same path, I could potentially have a nested array but I figure there must an easier solution I'm missing. Thanks for the help!
write a JOIN query and get all the data in one query then you can sort on the customers name as I think you are asking to do.
This will improve performance as well as simplify the code.
$getInfo = "SELECT dj.id, dj.customer, dj.job_name, dj.haul_info
c.name
FROM dispatch_jobs dj
LEFT JOIN customer c ON c.id = dj.customer
WHERE (:mydate BETWEEN dj.delivery_date AND dj.delivery_date_end)
ORDER BY c.name, dj.job_name";
$result=DB::run($getInfo, ['mydate' => $myDate]);
while($row=$result->fetch(PDO::FETCH_BOTH)) {
if(!empty($row['haul_info'])) {
$haulinfo = "($row[haul_info])";
}else{
$haulinfo = "";
}
if($checkit == $row['id']){
$woot = 'selected=selected';
}else{
$woot = '';
}
$activeProjectDropdown.="<option value='$row[customer]|$row[id]' $woot>$row[name] $haulinfo</option>\n";
}
Try this:
SELECT ... ORDER BY customer ASC, job_name
This sorts everything by costumer (ascending) first, and then by job_name (ascending, which is the default) whenever the costumer fields for two or more rows are equal.
more info here

How to get specific data from table1, use it in table2

I'm trying to get specific rows in table 1 (stellingen). I want to store these rows to specify the rows im interested in for the second table (stelling). So lets say table 1 has 5 rows where stelling ID matches REGIOID = 5. These IDS from stelling ID I want to use to fetch the data from the second table. see the code to see what I tried. I'm not managing to find a way in order too make this happen.
So maybe too be clearer because people always say im not clear:
There are two tables. they both have a matching column. Im trying to tell the second table I want data but only if it matches the data of the first table. Like a branch of a tree. Then, I want to output some data that's in the second table.
I've tried something like this before:
SELECT
*
FROM
table2
LEFT JOIN
table1 ON
table1.ID = table2.table1_id
I've tried to create a while loop to get the data before(after the first if statement and the last += was for the variable $amountofstellinge):
$amountOfStellinge = 0;
while ($amountOfStellinge<5){
mysqli_data_seek($result, $amountOfStellinge);
Here is the code what it looks like now, its wrong, i've been messing with t a lot, but maybe it shows you what I'm trying to achieve better.
if($result = mysqli_query($con, "SELECT * FROM stellingen WHERE REGIOID=1;")) {
$row = mysqli_fetch_assoc($result);
$stellingid= $row["Stelling_ID"];
//checking.. and the output is obviously not what I want in my next query
printf($stellingid);
//defining the variable
$Timer=0;
$sql1="SELECT * FROM stelling WHERE stelling_iD=$stellingid ORDER BY Timer DESC;";
$records2 = mysqli_query($con, $sql1);
$recordscheck = mysqli_num_rows($records2);
//max 5 data
if ($recordscheck < 5){
while ($stelling = mysqli_fetch_assoc($records2)){
//At the end, i would like to only have the data that is most recent
$Timer = date('d F', strtotime($stelling['Timer']));
echo "<p><div style='color:#ED0887'>".$Timer.":</div><a target = '_blank' style='text-decoration:none' href='".$stelling['Source']."'>".$stelling['Title']."</a></p>";
}}
$recordscheck+=1; } // this is totally wrong
EDIT:
I've tried this, #noobjs
$Timer=0;
$sql1="SELECT
*
FROM
stelling
LEFT JOIN
stellingen
ON
stelling.ID = stellingen.stelling_id
WHERE
stellingen.REGIOID=1
ORDER BY stelling.Timer LIMIT 5 DESC ;";
$records2 = mysqli_query($con, $sql1);
printf($records2);
while ($stelling = mysqli_fetch_assoc($records2)){
$Timer = date('d F', strtotime($stelling['Timer']));
echo "<p><div style='color:#ED0887'>".$Timer.":</div><a target = '_blank' style='text-decoration:none' href='".$stelling['Source']."'>".$stelling['Title']."</a></p>";
}
with this error:
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in
EDIT for more clarification
Here is some sample data
The expected results is:
every page has uses data from a different REGIOID. I expect the page to show data from the table stelling(Table 1). Accordingly to the REGIOID (Table2)
if i understand right:
SELECT
*
FROM
stelling
LEFT JOIN
stellingen
ON
stelling.stellingID = stellingen.stelling_id
WHERE
stellingen.REGIOID=1
ORDER BY stelling.Timer DESC LIMIT 5 ;

How to get a field from a result set and print as a string to the page (php/mysql/phpbb)

Im trying to make a custom function for my forum based on php. I have my index landing style page separate to my phpbb forums. I am trying to display the latest registered users username, as part of a statistics type widget for the home page. I have the following code so far:
//Function code
//Total Posts calculation
$result = $mysqli->query("SELECT DISTINCT post_id FROM phpBB_posts
WHERE post_id <= '1'");
$total_posts = $result->num_rows;
//Total topics calculation
$result2 = $mysqli->query("SELECT DISTINCT topic_id FROM phpBB_topics WHERE topic_id <= '1'");
$total_topics = $result2->num_rows;
//Member count calculation
$result3 = $mysqli->query("SELECT DISTINCT user_id FROM phpBB_users WHERE user_id <= '1'");
$total_members = $result3->num_rows;
//Newest member
$result4 = $mysqli->query("SELECT * FROM phpBB_users WHERE group_id <> 6 ORDER BY user_regdate DESC LIMIT 1");
$newestMember = $result4->name;
//End of function
//function output
printf("Total Posts: ".$total_posts."<br/> Total Topics: ".$total_topics."<br/>Total Members: ".$total_members."<br/>Our newest member is: ".$newestMember);
The "Newest member" section is where i'm having trouble, the rest works as I want, if you have any pointers/criticism i'll gladly take it on board though.
I want to be able to return the value in the username column from the results set i get returned from that query, and print it as the variable $newestMember.
My logic as you can see was to get the list of users, so SELECT * then limit the list to actual users and exclude bots etc so WHERE group_id <> 6. Then sort the list by the registered date ORDER BY user_regdate and then only one row from the full list with DESC LIMIT 1. I've been checking mysql and php documentation and can't work out how to get the value from the returned row/username column (field) and store it as the newestMember variable and print to the page.
Can anyone point me in the right direction please?
Cheers, Jamie
Managed to get it working modifying that code a little, deleted the mysqli->query that prepended the SELECT query and that made it work. What finally worked is as per below if anyone else comes across the same issue. Thanks for the nudge in the right direction CBroe! Needed a fresh pair of eyes and to look at it from a different angle :)
//Newest member
$myresult = ("SELECT * FROM phpBB_users WHERE user_type <> 2 ORDER BY user_regdate DESC LIMIT 1");
if ($result = $mysqli->query($myresult)) {
/* fetch object array */
while ($row = $result->fetch_row()) {
$newestMember = $row[7];
}
/* free result set */
$result->close();
}
//End of function
//function output
printf("Total Posts: ".$total_posts."<br/> Total Topics: ".$total_topics."<br/>Total Members: ".$total_members."<br/>Our newest member is: ".$newestMember);

Combine two SQL query in a while loop

Basically, I want to display the combined output of the below sql queries in a table using one while loop. I have a table called participating_institutions which holds unique code and names for all institutions. I also have trades table where each of the institutions can either be a buyer, a seller or both (Yes, an institution can do a trade for its two clients). With the help of good guys here, I was able to match each code in trades table with corresponding names in participating institution table using sql JOIN as indicated in the queries. The first query below will sum all the buy values for each firm and the second query will do same for their sales. However, the table I want to display will have the [Sum(buy_value) + Sum(sell_value)] for each firm in the while loop. How do I achieve this using either mysql or php.
Note: The trade table has two column in it for buy_firm_code and sell_firm_code. The records they hold is the same depending on which side of the trade a firm participated.
Below is what I have done so far.
<?php
$con=mysqli_connect("localhost","db_user","password","database");
$total_value = 0;
$buy_value = 0;
$sell_value = 0;
$firm_name = "";
$institution_code = "";
$display = "";
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$buy_sql="SELECT p.institution_code, p.institution, SUM(t.trade_value)
value_bought FROM trades t JOIN participating_institutions p ON p.institution_code = t.buy_firm_code GROUP BY t.buy_firm_code ORDER BY value_bought DESC";
if ($buy_result = mysqli_query($con, $buy_sql))
{
// Fetch one and one row for buy side
while($row=mysqli_fetch_array($buy_result)) {
$buy_value .= $row['value_bought'].'<br>';
$institution_code .= $row['institution_code'].'<br>';
$firm_name .= $row['institution'].'<br>';
}
}
$sell_sql = "SELECT p.institution_code, p.institution, SUM(t.trade_value) value_sold FROM trades t JOIN participating_institutions p ON p.institution_code = t.sell_firm_code GROUP BY t.sell_firm_code ORDER BY value_sold DESC";
if ($sell_result = mysqli_query($con, $sell_sql))
{
// Fetch one and one row for sale side
while($row=mysqli_fetch_array($sell_result)) {
$sell_value.= $row['value_sold'].'<br>';
$institution_code .= $row['institution_code'].'<br>';
$firm_name.= $row['institution'].'<br>';
}
}
$total_value = $buy_value + $sell_value;
$display .= '<table><tr><td>'.$institution_code.'</td><td>'.$firm_name .'</td><td>'.$total_value.'</td></tr></table>';
echo $display;
// Free result set
mysqli_free_result($buy_result);
mysqli_free_result($sell_result);
mysqli_close($con);
?>
When I run this two problems:
The firms repeat, I guess because I am running two queries. What I
want is one output record for each firm.
I don't get the overall total for each firm rather I get the sum of total buy and total sell of the first record
instead of
Firmcode A: FirmName A: 20,000
Firmcode B: FirmName B: 40,000
Firmcode C: FirmName C: 50,000
I get this
Firmcode A: FirmName A:
Firmcode B: FirmName B: 20,000
Firmcode C: FirmName C:
Thanks guys. I have been able to resolve the issue. I created two views in my database using the two queries above. I then used a third query in my code to join the two views using the SUM aggregate function for my total buy and total sell values. It works perfectly now. Thanks for all your contribution.

Php lottery issues multi winner problems

I have created a lottery script in php. My problem is now selecting more then one winner. Because it is possible for players to have the same number on their tickets. Here I am supplying the two table structures and the source code.
lotto_game {
id(int)
jackpot(int)
status(varchar10)
pick_1(int)
pick_2(int)
pick_3(int)
pick_4(int)
pick_5(int)
tickets_sold(int)
winner(text)
}
lotto_picks {
lotto_id(int)
user_id(int)
choice_1(int)
choice_2(int)
choice_3(int)
choice_4(int)
choice_5(int)
ticket_status(int)
}
These are my two tables with in my database. For examples sake we will create 2 users with the id's 1, and 2. So what happens is when the script runs it is suppose to change the lotto_game status from 'active' to 'finished' then add the random lottery numbers into each pick_* column.
$one = rand(1,30);
$two = rand(1,30);
$three = rand(1,30);
$four = rand(1,30);
$five = rand(1,30);
mysql_query("UPDATE `lotto_game` SET
pick_1 = '$one',
pick_2 = '$two',
pick_3 = '$three',
pick_4 = '$four',
pick_5 = '$five',
status = 'finished'
WHERE status = 'active'");
That wasn't too hard I will admit. But this is just the beginning of the end.
$lotto['tickets'] = mysql_query("SELECT ticket_id FROM `lotto_picks` WHERE ticket_status='valid'");
#$lotto[winners] = mysql_query("SELECT ticket_id,user_id FROM `lotto_picks` WHERE choice_1 = '$one' AND choice_2 = '$two' AND choice_3 = '$three' AND choice_4 = '$four' AND choice_5 = '$five'");
$lotto['num_tickets'] = mysql_num_rows($lotto['tickets']);
#$lotto[winner_id] = mysql_fetch_array(#$lotto[winners]);
$lotto['jackpot'] = mysql_query("SELECT jackpot FROM `lotto_game` WHERE status='active'");
$lotto['winner_jackpot'] = mysql_fetch_array($lotto['jackpot']);
$lotto['num_winners'] = mysql_num_rows($lotto['winners']);
//echo #$lotto['num_tickets'];
//echo #$lotto['num_winners'];
$winner = $lotto['num_winners'];
//echo #$lotto['winner_id']['user_id'];
$jackpot = $lotto['winner_jackpot']['jackpot'];
$id = #$lotto[winner_id][user_id];
if ($winner == 1) {
mysql_query("UPDATE `character` SET
decivers = decivers +'$jackpot'
WHERE user_id='$id'");
}
This is what I have come up with and it really seems to work with one winner. But I just cant figure out where to go from here. I have tried using some arrays but nothing works. I know what needs to be done but can't figure out how to do it.
When I search for winners I need to put into an array all their user id's.
so extra decivers is money, if anyone is confused on that. The status on the tickets doesn't really matter here but if you must know it just determines if the ticket_status is 'valid' or 'invalid'
i think you've chosen the wrong storage formats for your picked numbers. The standard approach is to use binary values which have N-th bit set if the number N is choosen.
Consider this example: user chooses numbers "2 4 5 9 11". Setting corresponding bits to 1 gives '10100011010' which is decimal 1306. Now the lottery picks "4 7 9 12 13" which is '1100101001000' == 6472. Perform a bitwise AND on both values and count the number of bits set in the result:
SELECT BIT_COUNT(1306 & 6472)
this immediately tells us that the user has 2 correct picks. Just as easy you can select "full" winners:
SELECT * FROM tickets WHERE BIT_COUNT(tickets.pick & lotto.pick) = 5
or sort the tickets by the number of correct picks
SELECT * FROM tickets ORDER BY BIT_COUNT(tickets.pick & lotto.pick) DESC
$winners_array = array();
if(mysql_num_rows($lotto['winners'])!=0){
while($row =mysql_fetch_array($lotto['winners'])){
if(!in_array($row['user_id'],$winners)) $winners[] = $row['user_id'];
}
}
$winners will be an array with all the winners user_ids

Categories