I am trying to order data from the table 'tech_inquiry' by the Field 'number' in descending order. This should put the results in order by year. Each 'number' field corresponds to another field with a title/date (what is actually viewed by visitors) which I can't sort by because the date is at the end of the title and not always in the same place.
Also, the table 'tech_inquiry_allowed' determines what is viewable to who when logged in.
With that said, here is the code:
<?
$query2=mysql_query("SELECT * FROM tech_inquiry_allowed where term_code = '$term_code' ");
while($row2=mysql_fetch_assoc($query2))
{
$id2=$row2['id'];
$query3=mysql_query("SELECT * FROM tech_inquiry WHERE id= '$id2' ORDER BY number DESC");
$row3=mysql_fetch_assoc($query3);
$name3=$row3['name'];
?>
<hr />
<li><? echo $name3; ?> </li>
<?
}
?>
Also, I have another 'admin' section that is able to order data correctly. The only difference is there is no conditional 'where' clause because no user authentication is needed (it is used to add data to the table).
Here is that code:
<?
$query2= mysql_query("SELECT * from tech_inquiry ORDER BY number DESC");
while($row2=mysql_fetch_assoc($query2))
{
$id2=$row2['id'];
$name2=$row2['name'];
?>
<hr />
<li><? echo $name2; ?> </li>
<?
I am wondering if it might be the fact that we are running a query inside a loop.
There are a number of problems here. First of all you only need one query to accomplish this. Please read up on SQL query writing when you get a moment. You will find it to be VERY helpful.
Second, you are using way more code than you need to. Below is the much simplified, cleaner, and probably faster code.
<?php
$query = mysql_query("SELECT * FROM tech_inquiry ti WHERE id IN (SELECT id FROM tech_inquiry_allowed where term_code = '$term_code') ORDER BY ti.number");
while ($row = mysql_fetch_object($query)) {
echo "<hr />\n<li><a href='get_file.php?id={$row->id}'>{$row->name}</a></li>";
}
?>
You are not looping the inner query. Anyway, you should be using a single query for this:
SELECT allowed.*, inquiry.*
FROM tech_inquiry_allowed allowed
INNER JOIN tech_inquiry inquiry
ON inquiry.id = allowed.id
WHERE term_code = '$term_code'
ORDER BY inquiry.number DESC
Related
I am making an extremely basic posting system, and I cant seem to figure out how to get the most recent rows from a certain table. I have tried other solutions offered here, but my posts were randomly placed. How would I accomplish this? My code is below.
function load_posts(){
$posts_sql = "SELECT * FROM posts";
$posts_result = Phoenix\Database\Database::$database->query($posts_sql);
while($row = $posts_result->fetch_assoc()){
$posts_display = '
<div class = "card" style = "width:500px">
<div class = "card-body">
<div class = "card-title">'. $row['username'] .'</div>
<p>'. $row['content'] .'</p>
</div>
</div>
';
echo $posts_display;
}
}
Again, I want the posts to be displayed from most recent, to old.
You need to have information in each row that captures this information. The most common suspects are:
an auto-incrementing id
a creation date
Then you just ask the database to sort the results. For instance, if post_id is an auto-incremented id:
select p.*
from posts p
order by p.post_id;
SELECT * FROM TableName ORDER BY id DESC
// order by should be with primary key
I need to display table of contents from bottom to top. Since when a new row is inserted, it appears at bottom and when I access it using mysqli_fetch_array it shows the most recent inserted row at the bottom. The code is like this:
<?php
$abc = mysqli_connect("localhost","root","","members") or die(mysqli_error($abc));
$select_query = "SELECT title, url, photographer, genere, timestamp FROM gallery";
$select_query_result = mysqli_query($abc, $select_query) or die(mysqli_error($abc));
?>
And somewhere in html, this code appears.
<ol class="pictures">
<?php while($row = mysqli_fetch_array($select_query_result)) { ?>
<li class="thumbnail" data-div="<?php echo $row['genere'] ?>,<?php echo $row['photographer'] ?>,<?php echo $row['title'] ?>,<?php echo $row['timestamp'] ?>" style="background-image: url(<?php echo $row['url'] ?>)">
</li>
<?php } ?>
</ol>
So, what should I do to display it in reverse order so that I can get the most recent entry on top while displaying.
Simply order your SQL Query by using either
ORDER BY attribute ASC/DESC
So for example if you want the most recent entry on top, simply change your SQL query to:
"SELECT title, url, photographer, genere, timestamp FROM gallery ORDER BY timestamp desc"
And it should work. You can do this with any attribute you want. I recommend to do it with the primary key (ID) if you have one, but since you're not selecting it, you can do it with your timestamp too.
https://www.tutorialspoint.com/sql/sql-sorting-results.htm
Just Modify Your SQL Query
Use ORDER BY
SELECT title, url, photographer, genere, timestamp FROM gallery ORDER BY id DESC ;
If you doesn't want to use ORDER BY:
for($i = count($select_query_result), $i > 0; $i--) {
// Actions
}
Use Order By:
<?php
$abc = mysqli_connect("localhost","root","","members") or die(mysqli_error($abc));
$select_query = "SELECT title, url, photographer, genere, timestamp FROM gallery ORDER BY timestamp DESC";
$select_query_result = mysqli_query($abc, $select_query) or die(mysqli_error($abc));
?>
$query=mssql_query ('SELECT USER_INDEX_ID FROM T_o2jam_login');
echo "<table border =\"0\" style=\"color: gray;\" cellspacing=\"0\" cellpadding=\"0\" CLASS='boldtable'><tr><th colspan=\"9\">Online Players</th></tr><tr><td>Level </td> <td> Nick </td> </tr>";
if (mssql_num_rows($query)) {
while ($row = mssql_fetch_array($query)) {
$q2 = mssql_query ("select * from t_o2jam_charinfo where USER_INDEX_ID=$row[USER_INDEX_ID] ORDER BY Level DESC");
$nt=mssql_fetch_array($q2);
echo "<tr><td>Lv. $nt[Level] </td><td> $nt[USER_NICKNAME] </td></tr>" ;
I am trying to sort online users by Level on Descending order. From 99 to Level 1. It displays the data but they are not sorted. What's the problem right there? Thank you!
You need to have the order by in your first query. Your second query is within a loop, so it's going to first go by the order of the first one.
This really should be one query with a JOIN.
SELECT charinfo.*, FROM t_o2jam_charinfo charinfo
INNER JOIN T_o2jam_login login
ON charinfo.USER_INDEX_ID = login.USER_INDEX_ID
ORDER BY `Level` DESC
But since you never use any of the info from the "login" table, one wonders why it's even used at all.
Anyway, never run queries in loops.
ok so i coded in a news section and everytime i insert new news,its shows below the old one.
i want to make it ORDER BY id but make it start like backwards.i dont know how to explain but yeh
i want them to be ordered by the newest added by the id so if the 1st row that was inserted's id is 1 then i want it to show below the next id.
so row with id = 2 will be here
so row with id = 1 will be here
thats how i want it to be, instead of it being like this
so row with id = 1 will be here
so row with id = 2 will be here
.
Sorry for my bad explanation i hope this is understandable
heres my code so far
<?php
require("include/config.php");
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id");
while($row = mysql_fetch_array($sqlnews)) {
$dbdate = $row['date'];
$dbnews = $row['news'];
echo "<h1><strong>$dbdate</strong></h1>";
echo "<div class='content'>$dbnews</div><br><br>";
}
?>
add DESC in your ORDER BY clause
SELECT * FROM news ORDER BY id DESC
by default, it is in ASC mode.
SELECT * FROM news ORDER BY id DESC
DESC is the descending keyword ASC is ascending
If you specify neither then default behaviour is ascending
Just use DESC keyword in your sql query.
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id DESC");
However, it isn't really such a good idea to use id, because semantically, there is nothing preventing somebody from changing the sequence which counts up automatically assigning the ID.
Therefore, you should add a column created_at. Everytime you insert a row, you can use the SQL function NOW().
The advantage is that you can say:
SELECT * FROM news WHERE created_at <= NOW() ORDER BY created_at DESC
This means that you can schedule news items ahead of time, and it will automatically display when the date/time arrives!
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id DESC");
try this:
just have to add
order by id DESC
Just replace your code by this code:
<?php
require("include/config.php");
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id DESC");
while($row = mysql_fetch_array($sqlnews)) {
$dbdate = $row['date'];
$dbnews = $row['news'];
echo "<h1><strong>$dbdate</strong></h1>";
echo "<div class='content'>$dbnews</div><br><br>";
}
?>
I have searched high and low and cant find a similar issue to what i have.
I am a beginner so please forgive my clunky query structure.
I am trying to ( have attached screen grab below of output ):
Query the photos table to get the id based on category id and also start,limit because of pagination.
Query the photos tagged table based on the photo id i just got from the first query.
But my problem is that i cant group the tags, some photos have the same tag name. And the output just shows all the tags for each photo. I want restaurant to show only once etc...
<?php
// Get the file ideez and dont go beyond pagination start,limit eg:30,10
$queryFile = "SELECT id FROM $tableName WHERE cat_id=".$fileID." LIMIT $start, $limit";
$resultFile = mysql_query($queryFile);
while ($rowFile = mysql_fetch_array($resultFile)) {
// Get the tag names based on the file ideez retrived from the above query
$queryTagged = "SELECT tag_name FROM photoTagged WHERE file_id=".$rowFile['id']." GROUP BY tag_name";
$resultTagged = mysql_query($queryTagged) or die(mysql_error());
while ($rowTagged = mysql_fetch_array($resultTagged)) {
$tagged = $rowTagged['tag_name'];
?>
<li><a href="#"><?php echo $tagged; ?></li>
<?php }} ?>
the above query is producing:
bar,cappucino,coffee,coffee machine,restaurant,bar,cappucino,coffee,coffee machine,restaurant,bar,coffee,restaurant,bar,coffee,coffee machine
restaurant,bar,cappucino,coffee,restaurant
what i need to show is:
bar,cappucino,coffee,coffee machine,restaurant
If anyone could help i would greatly appreciate it.
Thank you in advance.
John
My new code is
<?php
// Get the file ideez and dont go beyond pagination start,limit eg:30,10
$queryFile = "SELECT id FROM $tableName WHERE cat_id=".$fileID." LIMIT $start, $limit";
$resultFile = mysql_query($queryFile);
while ($rowFile = mysql_fetch_array($resultFile)) {
// Get the tag names based on the file ideez retrived from the above query
$queryTagged = "SELECT DISTINCT tag_name FROM photoTagged WHERE file_id=".$rowFile['id'];
$resultTagged = mysql_query($queryTagged) or die(mysql_error());
$rowTagged = mysql_fetch_array($resultTagged);
$tagged = $rowTagged['tag_name'];
?>
<li><a href="#"><?php echo $tagged; ?></li>
<?php } ?>
I now get this: ( So i am close arent i? )
----------
cappucino
restaurant
bar
coffee machine
restaurant
coffee
coffee
restaurant
restaurant
restaurant
coffee
coffee
restaurant
restaurant
coffee machine
restaurant
coffee
I wonder if the spaces are something? i got that from copy and paste...
Any further help would be appreciated :-)
You should first perform a join between your photos and tags table, and THEN select the distinct tags.
I believe this query will let the database do all the work for you:
SELECT DISTINCT tag_name
FROM (SELECT file_id FROM $tableName WHERE cat_id=$fileID LIMIT $start, $limit) t1
LEFT JOIN photoTagged ON t1.id = photoTagged.file_id
You can also sort the tags in the database (ORDER BY tag_name).
Haven't tried it myself, so maybe the syntax is a bit off. But the idea should work.
distinct doesnt work if you are only getting one record at a time, so put the data in a PHP array and then use array_unique, which is PHPs way to do distinct
<?php
// Get the file ideez and dont go beyond pagination start,limit eg:30,10
$queryFile = "SELECT id FROM $tableName WHERE cat_id=".$fileID." LIMIT $start, $limit";
$resultFile = mysql_query($queryFile);
while ($rowFile = mysql_fetch_array($resultFile)) {
// Get the tag names based on the file ideez retrived from the above query
$queryTagged = "SELECT tag_name FROM photoTagged WHERE file_id=".$rowFile['id'];
$resultTagged = mysql_query($queryTagged) or die(mysql_error());
$rowTagged = mysql_fetch_array($resultTagged)
$tagged[] = $rowTagged['tag_name'];
}
// Let PHP do the work.
$tagged=array_unique($tagged);
while (list(,$val) = each($tagged)) {
echo "<li><a href="#">$val</li>
}
?>
you need to do a sub-query to dodge the pagination problems with the photos. If you wish the selected tags to be a subset of the photos found in your first query, then you will need to do the following.
<?php
$queryTagged = "SELECT TAG.tag_name, count(TAG.tag_name) AS num FROM photoTagged as TAG JOIN (SELECT id FROM $tableName WHERE cat_id=$fileID LIMIT $start, $limit) as PHOTO ON (PHOTO.id = TAG.file_id) GROUP BY TAG.tag_name";
$resultTagged = mysql_query($queryTagged) or die(mysql_error());
while ($tagged = mysql_fetch_assoc($resultTagged)) {
echo "<li id="'.$tagged['TAG.tag_name'].'"><a href="#">".$tagged['TAG.tag_name']." (".$tagged['TAG.num'].")</li>";
}
?>
This way you will have two queries, on for finding the photos, and one for finding the tags for the photos on that page. This technically takes a little longer as MySQL has to load the query into a temporary table, but it should work fine.
SELECT DISTINCT tag_name FROM photoTagged WHERE file_id=".$rowFile['id'] ?