Cannot sort by including the date - php

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

Related

SELECT userinformation where userid is in the most rows

I have a table that contains the same userid multiple times.
I would like to return the picture of 9 users that have the most rows with their userid in it.
How can I select the user with the most rows and the ones following (from most to least)?
It's probably something easy but I can't find an answer.
$sql ="SELECT * FROM beoordelingen,users WHERE beoordelingen.userid=users.userid
GROUP BY beoordelingen.userid LIMIT 9 ";
$result = $conn->query($sql) or die ("The query could not be completed. try again");
$cols=3;
echo "<table width='150' border='0' cellpadding='0'>"; // The container table with $cols columns
do{
echo "<tr>";
for($i=1;$i<=$cols;$i++){ // All the rows will have $cols columns even if
// the records are less than $cols
$row=mysqli_fetch_array($result);
if($row){
echo"<td>
<table width='150' border='0' cellpadding='0'>
";
if ($row["userimage"] == '') {
echo "<a href='user.php? id=" . $row['userid'] . "'</a><img src='Images/users/nopicture.png' alt='nopicture'
class='userimage-tooltip-large' title='".$row['username']."''>";
} else {
echo "<a href='user.php? id=" . $row['userid'] . "'</a><img src='Images/users/".$row['userimage']."'
class='userimage-tooltip-large' title='".$row['username']."''>";
}
echo"</table>
</td>";
} else {
echo "<td> </td>"; //If there are no more records at the end, add a blank column
}
}
} while($row);
echo "</table>";
Add a count of the rows with the userid, order by that descending and then use the limit:-
SELECT users.userimage,
users.userid,
users.username,
COUNT(*) AS userid_count
FROM beoordelingen
INNER JOIN users
ON beoordelingen.userid=users.userid
GROUP BY beoordelingen.userid
ORDER BY userid_count DESC
LIMIT 9
Note that which values you get of the columns other than the userid is not defined. If you want the values from a particular row then this is a bit more complicated and you need to define which one.

sort my display data based on their user role

hi i already can make search. now how i want to put that data based on their role, based on this picture i want to make admin ,admin , user, user,user. need to use sort by ? i dont know.
and this my coding search . where should i put sort by ?
<?php
include 'config1.php';
if(isset($_POST['search'])){
$searchTerm = $_POST['search'];
$query = "SELECT * FROM members WHERE userid LIKE '%$searchTerm%'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
echo "<table height = '30%'border='1'>";
if($count == 0)
{
echo "NO ID REGISTERED!";
}
else
{
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td width='5%'><b>USER ID:</b> {$row['userid']} </td>";
echo "<td width='5%'><b>USER NAME :</b> {$row['username']} </td>";
echo "<td width='5%'><b>USER EMAIL:</b> {$row['useremail']} </td>";
echo "<td width='5%'><b>USER ROLE:</b> {$row['userrole']} </td>";
echo "<td width='5%'><b>USER DIVISION:</b> {$row['userdiv']} </td>";
echo "<td width='5%'><b>USER DEPARTMENT:</b> {$row['userdepartment']} </td>";
echo "</tr>";
}
}
echo"</table>";
}
?>
$query = "SELECT * FROM members WHERE userid LIKE '%$searchTerm%' ORDER BY userrole";
Also can use ASC or DESC for displaying in ascending or descending order after ORDER BY.
eg.
Select * from users WHERE choice = 'PHP' ORDER BY id ASC;
$query = "SELECT * FROM members WHERE userid LIKE '%$searchTerm%' order by fieldWhichYouWant";
OR
$query = "SELECT * FROM members WHERE userid LIKE '%$searchTerm%' ORDER BY userrole ASC";
or add ASC or DESC as Ascending or descending oder to sort.
Replace fieldWhichYouWant with your requirement.

Sorting from 2nd query OR functioning join query

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.

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 ordered list from latest post

I have 3 divisions in my table, first is the "ID", second is the "TOPIC", then lastly is the "DATE POSTED". I have this prob, I can't make the new topic be on top. it just goes on the last of the list. Now, how can I make the latest topic that I posted be on top of my lists?
my codes:
$query = mysql_query("SELECT * FROM PythoN_Blog")or die(mysql_error());
echo "<table border='0' width='700'>";
while($result = mysql_fetch_array($query))
{
echo "<tr>";
echo "<td align='center' style='padding-left:30;'>".$result['id']."</td>";
echo "<td align='center' style='padding-left:10;'><a href='#'>".$result['topic']."</a></td>";
echo "<td align='center'>".$result['date']."</td>";
echo "</tr>";
}
echo "</table>";
Change your query to this
"SELECT * FROM PythoN_Blog order by DATE_POSTED DESC";
if your DATE_POSTED column is NOT datetime format (e.g. varchar) then you have to convert it:
"SELECT * FROM PythoN_Blog ORDER BY CONVERT(DateTime, DATE_POSTED,103) DESC"
if your DATE_POSTED column is datetime format then:
"SELECT * FROM PythoN_Blog ORDER BY 'DATE_POSTED' DESC";

Categories