Sorting from 2nd query OR functioning join query - php

i currently have a table i need displayed like this:
but as you can see, its not sorted on "amount dropped" (named $amount and amount in the code)
i first need to gather the names and drop_id's from a table. which is done like this:
//----------------FETCH ALL CONTENTS FROM DROPTABLE TO DISPLAY DROPS------------\\
$query = "SELECT * FROM droptable
WHERE boss_id = ". $boss ."";
$stmt = $pdo->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $row){
$drop_id = $row['drop_id'];
$drop = $row['dropname'];
$boss_id = $row['boss_id'];
$picture = $row['picture'];
this fetches the name of the drop(dropname). the id for it (drop_id), the boss id (boss_id) and the picture for it (picture).
it then goes on to check if ive ever logged a drop from the boss from another table:
//----------------FETCH ALL LOGGED DROPS FOR DISPLAYING AMOUNT------------\\
$query1 = "SELECT * FROM dropcounter
WHERE boss_id = ". $boss ." AND userid = ". $user ." AND drop_id = ". $drop_id ."";
$stmt1 = $pdo->prepare($query1);
$stmt1->execute();
$result1 = $stmt1->fetchAll(PDO::FETCH_ASSOC);
echo "<tr>";
echo "<td><img src='../images/". $picture ."'</td>";
echo "<td>". $drop . "</td>";
echo "<td>". $amount ."</td>";
echo "<td>". $percent ."</td>";
echo "<form action='logger.php' method='post'>";
echo "<td><input type='hidden' value=". $drop_id ." name='drop_id'>";
echo "<input type='hidden' value=". $boss_id ." name='boss_id'>";
echo "<input type='hidden' value=". $user ." name='user'>";
echo "<input type='submit' value='Add'></td>";
echo "</tr>";
echo "</form>";
this does everything i want exept sort on amount dropped or drop percentage (since they will sort the same). ive tried adding "ORDER BY amount DESC" in the 2nd query but it didnt sort.
ive also tried using JOIN, but it didnt come close to the result i wanted and i got stuck for 3 days on the query so went with the above code instead. but im willing to use join again if my wished result can be done.
here's the JOIN code that doesnt work:
$query = "SELECT dropcounter.drop_id, dropcounter.boss_id, dropcounter.add_date, dropcounter.username, dropcounter.amount, droptable.drop_id, droptable.dropname, droptable.boss_id, droptable.wiki_link, droptable.picture
FROM droptable
JOIN dropcounter
ON droptable.boss_id = dropcounter.boss_id
WHERE dropcounter.drop_id = droptable.drop_id AND droptable.boss_id = ". $boss ." AND dropcounter.username = ". $user ."
ORDER BY dropcounter.amount";
here's the structure i have on my tables:
DROPCOUNTER TABLE:
and here's DROPTABLE table:
if anyone would be able to help me with either one if them i would be very glad for your kindness!
here's a fiddle if anyone wanna try it out. ive imported some sample data: http://sqlfiddle.com/#!2/d66846/1/0

You need to use LEFT JOIN if you want to get rows from droptable that don't have a match in dropcounter. All the tests that refer to dropcounter have to be in the ON clause, otherwise the null matches will cause the tests to fail and those rows will be filtered out.
SELECT dc.add_date, dc.username, IFNULL(dc.amount, 0) amount, dt.drop_id, dt.dropname, dt.boss_id, dt.wiki_link, dt.picture
FROM droptable dt
LEFT JOIN dropcounter dc
ON dt.boss_id = dc.boss_id AND dc.drop_id = dt.drop_id AND dc.userid = $user
WHERE dt.boss_id = $boss
ORDER BY amount
DEMO

You're trying to use in joined statement:
dropcounter.username = ". $user ."
which contains 2 errors:
1. there isn't field username in that table
2. you haven't enclosed string in ''
Change it to dropcounter.userid
Also you don't need to select droptable.drop_id and droptable.boss_id as it's already selected from dropcounter table.
EDIT: Based on your fiddle:
SELECT dropcounter.drop_id, dropcounter.boss_id, dropcounter.userid, dropcounter.amount, droptable.dropname
FROM droptable
JOIN dropcounter
ON droptable.boss_id = dropcounter.boss_id
WHERE dropcounter.drop_id = droptable.drop_id AND droptable.boss_id = 1 AND dropcounter.userid = 1
ORDER BY dropcounter.amount DESC;
It works and sorts without problem.

Related

Cannot sort by including the date

When I enter the vehicleID and Date, the records must be sorted by using both vehicle ID and Date, however it doesn't get sorted from the Date but only with the vehicleID. How can I achieve this ?
if ($vid != null && $datepicker != null) {
$conn = new Db();
$sql = "SELECT * FROM trip_details where vehicle_id = '".$vid."' AND date_t = '".$datepicker."'";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td> ". $row["trip_id"]."</td>";
echo "<td> ". $row["vehicle_id"]."</td>";
echo "<td> ". $row["total_trip_km"]."</td>";
echo "<td> ". $row["predict_fual"]."</td>";
echo "<td> ". $row["date_t"]."</td>";
// echo "<td><input type=\"submit\" value=\"view map\"></td>";
echo "</tr>";
}
}
SQL makes no guarantee on the order results are returned from a select query unless you explicitly add an order by clause, so the fact that you observe the returned records sorted by the vehicle_id is coincidental. You need to add an order by clause to the query:
ORDER BY vehicle_id, date_t
to sort you data by the columns you have define the name of columns in order by clause with order Acs(ascending) or Desc (descending)
e.g.
order by desc column1, asc column2
Order by needs to define to get the desired result.
try this
$sql="SELECT * FROM trip_details where
vehicle_id='".$vid."' AND date_t='".$datepicker."'
ORDER BY vehicle_id DESC,date_t DESC";

Grabbing info from two different tables, assistance

I am trying to make a members page. For the rank it shows numbers so I made another table that has the rank id (1,2,3 etc) and added a name to it also.
Here is my code.
<?php
$getCoB = mysql_query("SELECT * FROM `members`
WHERE `CoB` = '1' && `user_state` = '1' ORDER BY `id`");
$id = ($getCoB['rank']);
$rankInfo = mysql_query("SELECT * FROM `ranks` WHERE `id` = '".$id."'");?>
<h2 class="title">Council of Balance members</h2>
<style>tr:nth-of-type(odd) { background-color:#F0F0F0;}</style>
<div style='padding:5px;'>
<?php
if(mysql_num_rows($getCoB) == 0)
{
echo "There are no Council of Balance members.";
} else {
echo "<table cellpadding=20 width=100%>";
while($row = mysql_fetch_assoc($getCoB))
{
echo "<tr><td style='background-color:transparent;'><b>". $row['name']
. "</b></td><td>Rank: ".$rankInfo['name']." <br/> Role: ". $row['role']."</td>";
}
echo "</table>";
}
?>
The problem is rankInfo['name'] is not showing up. I tried to do something on this line while($row = mysql_fetch_assoc($getCoB)) and tried to make it something like this while($row = mysql_fetch_assoc($getCoB)) || while($rank = mysql_fetch_assoc($rankInfo) and changed this part <td>Rank: ". $rankInfo['name'] . " to this <td>Rank: ". $rank['name'] . " but I end up with an error. If I leave it like it is, it just shows Rank: without the name I added into my database.
You can combine your two queries into one using an inner join.
<?php
$getCoB = mysql_query("SELECT m.name as member_name, m.role, r.name as rank_name
FROM `members` as m INNER JOIN `ranks` as r ON m.rank = r.id
WHERE `CoB` = '1' && `user_state` = '1' ORDER BY m.id");
?>
Because of how INNER JOIN works, this will only display members who have corresponding records in the ranks table. If there are some members that you want to display that have no rank record, use LEFT JOIN instead.
Then when you echo out the data, be sure to refer to the item you have fetched ($row) each time. In your code, you are referring to $rankInfo['name'], where $rankInfo is not a variable, but a mysql query from which no rows have been fetched.
while($row = mysql_fetch_assoc($getCoB)) {
echo "<tr><td style='background-color:transparent;'><b>". $row['member_name']
. "</b></td><td>Rank: ". $row['rank_name'] . " <br/> Role: " . $row['role'] . "</td>";
}

PHP Returns No Rows When a Field is Empty

I have a while loop that iterates through the rows returned from a DB query.
Query
$sql = "SELECT t.barcode AS barcode, t.code, t.brand, t.name, t.cost, t.price, t.vat, SUM(n.stock) AS stock
FROM t
INNER JOIN c.am ON t.code=am.code
INNER JOIN n ON t.code=n.code WHERE (n.name='X' OR n.name='Y')
AND t.code IN ($in)
GROUP BY t.code, t.name, t.cost, t.salesprice, t.vat";
$result = $mysqli->query($sql);
echo "<table id='maintable'><tr><th>Barcode</th><th>Name</th><th>Brand</th></tr>";
while($row = $result->fetch_array()) {
if(empty($row['barcode'])){
$barcode = "none";
}
$barcode = $row['barcode'];
$name = $row['name'];
$brand = $row['brand'];
echo "<td>" . $barcode . "</td>";
echo "<td>" . $name . "</td>";
echo "<td>" . $brand . "</td>";
}
echo "</table>";
The problem is if barcode is empty (not in the DB table), no rows get displayed. However if there is a barcode, the row DOES display. In my example I have tried to check if $row['barcode'] is empty to assign a string so that the row will still display but its unsuccessful.
In the Table itself in the database, the Barcode has a Null field set to YES and Default Field set to NULL so I have also tried:
if(is_null($row['barcode'])) { ..... };
But unsuccessful.
Somewhere I read that empty can equate to: '', 0 and NULL so I'm thinking it's failing because checking if "empty" is the wrong approach?
Any help appreciated.
if(empty($row['barcode'])){
$barcode = "none";
} else {
$barcode = $row['barcode'];
}
or even better:
$barcode = empty($row['barcode'])?"none":$row['barcode'];
So your code would be:
while($row = $result->fetch_array()) {
$barcode = empty($row['barcode'])?"none":$row['barcode'];
$name = $row['name'];
$brand = $row['brand'];
echo "<td>" . $barcode . "</td>";
echo "<td>" . $name . "</td>";
echo "<td>" . $brand . "</td>";
}
UPDATE Not sure about your database structure, but if you need some empty t.barcode values your query could be like:
$sql = "SELECT
t.barcode AS barcode,
n.code,
t.brand, t.name, t.cost, t.price, t.vat,
SUM(n.stock) AS stock
FROM n
LEFT JOIN t
ON t.code=n.code
AND t.code IN ($in)
WHERE (n.name='X' OR n.name='Y')
GROUP BY n.code, t.name, t.cost, t.salesprice, t.vat";
And I don't understand what is INNER JOIN c.am ON t.code=am.code stands for, maybe you should delete it.
Your conditional logic is being followed by this line:
$barcode = $row['barcode'];
Whatever was assigned to $barcode previously is being overwritten.
Looks like you wanted that to be else, or you wanted that line before the conditional test.
As an alternative, you could just modify your query to return the string "none" in place of NULL with an IFNULL function, assuming that barcode is character type.
SELECT IFNULL(t.barcode,'none') AS barcode
, ...
FROM t
EDIT
The question has been edited (after I posted my answer), to add a SQL query to the question.
I thought the problem was that an empty (zero length) string was being assigned to a variable, and the intent was to replace the empty string with a literal.

Output distinct values in SQL column with PHP

I have a table with two collumns (shortened), NAME and CATEGORY.
I want to output the number of distinct categorys. For an examle: Sport : 5 , Houses : 10.
I use this one:
$test = mysqli_query($con,"SELECT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");
This work then I run the code in SQL Shell, but I have no clue on how to output it in PHP. I have searced Google up and down without any successfull solution.
Any help?
I want to output it in a table format.
EDIT: Here is my full code: (tablename is changed, and $con is removed)
$test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");
while($row = mysql_fetch_array($test)) {
echo $row['lkategori'] . ":" . $row['count'];
die("test");
}
$test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");
echo "<table border='1'>";
while($row = mysqli_fetch_array($test)) {
echo "<tr>";
echo "<td>" . $row['lkategori'] . "</td>";
echo "<td>" . $row['count'] . "</td>";
echo "</tr>";
}
echo "</table>";
This will output all the categories and the count returned by the sql statement into a table. Also as a sidenote you should look into PDO.
EDIT: to make sure you do get the distinct values you should use the DISTINCT keyword in your sql statement:
$test = mysqli_query($con,"SELECT DISTINCT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");
use this
while($row = mysqli_fetch_array($test)) {
echo $row['lkategori'] . ":" . $row['count'];
die("test");
}
Thanks

PHP: table structure

I'm developing a website that has some audio courses, each course can have multiple lessons. I want to display each course in its own table with its different lessons.
This is my SQL statement:
Table: courses
id, title
Table: lessons
id, cid (course id), title, date, file
$sql = "SELECT lessons.*, courses.title AS course FROM lessons INNER JOIN courses ON courses.id = lessons.cid GROUP BY lessons.id ORDER BY lessons.id" ;
Can someone help me with the PHP code?
This is the I code I have written:
mysql_select_db($database_config, $config);
mysql_query("set names utf8");
$sql = "SELECT lessons.*, courses.title AS course FROM lessons INNER JOIN courses ON courses.id = lessons.cid GROUP BY lessons.id ORDER BY lessons.id" ;
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<p><span class='heading1'>" . $row['course'] . "</span> </p> ";
echo "<p class='datum'>Posted onder <a href='*'>*</a>, latest update on " . strftime("%A %d %B %Y %H:%M", strtotime($row['date']));
}
echo "</p>";
echo "<class id='text'>";
echo "<p>...</p>";
echo "<table border: none cellpadding='1' cellspacing='1'>";
echo "<tr>";
echo "<th>Nr.</th>";
echo "<th width='450'>Lesso</th>";
echo "<th>Date</th>";
echo "<th>Download</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['nr'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . strftime("%d/%m/%Y", strtotime($row['date'])) . "</td>";
echo "<td><a href='audio/" . rawurlencode($row['file']) . "'>MP3</a></td>";
echo "</tr>";
echo "</table>";
echo "<br>";
}
?>
One thing that comes to mind is you're starting with lessons and pulling the course details over with it. That means you're going to have a new row per lesson with a joined course. You may want to sort by course (so they're grouped) then (in PHP) keep a tally of "current course". When the course changes, switch to new heading paragraph, table, etc.
Pseudo code:
$currentCourse = null; // intitialize the course
$query = your select sorted by course;
while ($row in $query)
{
if ($currentCourse != $row['course'])
{
if (!is_null($currentCourse))
{
// there was a course before it, close the current one
}
// begin setting up heading1, table beginning, etc.
$currentCourse = $row['course']; // set this as the active course
}
// dump the current row as a table entry
}
// close the table (same code as in the second if statement)
You close the while loop on line 8 of your code block. Remove that '}' on line 8.
Also the HTML element doesn't exists!
I think I know what's your problem. You need a while loop that loops al the "courses" and in that loop you execute a second query where you select the lessons where the course_id is equal to the current course id you're looping. A little dummy code for you.
<?php
while($row = mysql_fetch_assoc(mysql_query("SELECT * FROM courses"))) {
//display the course
while($row2 = mysql_fetch_assoc(mysql_query("SELECT * FROM lessons WHERE course_id=" . $row['id']))) {
//display the lessons of that course
}
}
?>

Categories