Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    PHP




Sorting Database Query Results


I want to know if it is possible to sort query results so that the records with a value in a certain field is displayed first and the records with the field empty thereafter.




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Sorting Query Results Into Groups
I have a 'staff' table with a column 'status', corresponding to a
'statuses' table with the appropriate titles (eg 1 | Editor in Chief).
I want to display on the page the headings (the titles from statuses)
along with all of the staff members with that status ID.

I've attempted this using a query for each possible status, which I
figure was pretty inefficient (plus it didn't work properly). The best
I could do manually was to just display a list of staff and their
statuses sorted in order of the title ranks.

Small Issue With Sorting Query Results.
In the below code I am simply trying to sort a list of results in the category "Drivers" by price. I can achieve this fine but it only seems to take the first 2 digits of the price when sorting, so... Instead of sorting like:

€38
€70
€125
€175
€250
€370

Its sorts like:

€125
€175
€250
€370
€38
€70

$limit = 'LIMIT ' .($pageno - 1) * $max .',' .$max;
$query = "SELECT * FROM ads WHERE category = 'Drivers' AND validation = 0 ORDER BY '$price' $limit";

$result = mysqli_query($mysql_connect, $query) or die (mysqli_error($mysql_connect));

Sorting XML Results
The following code parses an XML file and displays the results. The function resultSort is meant to sort the results by price from highest to lowest. Unfortunately, it's not sorting correctly in all cases. I think this may be due to the prices being in euros. Right now, this is how it outputs the results:


1 208,00
2 148,00
412,00
638,00
942,00

This is how it should look:

2 148,00
1 208,00
942,00
638,00
412,00

Here's the code: PHP Code:

Sorting Results
I hava a table with a primary key cod_topico and I'd sort my results.
I do this, ok?
$query='SELECT * from topico order by cod_topico asc' ;
But I would not sorting asc, How I sort a non-asc form? What is the oposite of asc?

Sorting Results
What I need to do is from the query I send sort the results by ID numbers from highest to lowest, because the highest number is the most recent news post I would like this to be printed first and then the lower the ID number the further down the post goes. Am I making sense? PHP Code:

Sorting Results By Header
What I am hoping to do is make the headers of the results column links, so that that when people click on them, the results on the page is automatically sorted alphabetically.

I found a tutorial on http://codewalkers.com/tutorials/21/2.html, however it seems that I would need to make several changes to my code that would then make the other parts of my script unworkable (is that even a word!?).

Here is my current search feature ; http://www.btinternet.com/~shahnawaz.khan/searchMD.htm . The headings I want to make sortable are Model, Creator and Book Title.

PHP Code:

Sorting Results Of Odbc_exec?
I am running a PHP program that connects to an Access 2000 database
via ODBC:
$results = odbc_exec($connection_id, $sql_select);

Is it possible to sort the contents of $results? I wish to use a
regex-based sort order that you can't do in Access 2000* SQL

Sorting Table Results
I tried searching Google for some stuff about sorting table results.
I want to be able to click the different headers and sort the results by each field. Anyone know some good sites/tutorials?

Sorting Results By Alphabet
I like to know how to sort and group results by alphabet. I have over 2800 flash games listed in my database and i want to grab the names and the id of each game, order them in alphabetical order then group them that way.

So the results will show like this..

A
A game
A game 2
A game 3

B
B game
B game 2
B game 3

C
C game
C game 2
C game 3

What would the query be?

ODBC Results Sorting And Adding?
I need to go through ODBC results and add Quantity for like items. Quick example:

Database Is:

ItemQntyDate
foo11-10-99
bar51-15-00
foo21-11-99

I need to somehow search through results and add matching Item Quantities together. In this example, the return I would expect is:

ItemQntyDate
bar51-15-00
foo31-10-99/1-11-99

because the foo Qnty added together became 3.

Any thoughts on how to accomplish this? Load the ODBC results into an array and somehow sort through the array? Never done that before...

Advice On Sorting Results (in A Table): Session Variables?
I have a table of query results (from PostgreSQL) that I am displaying using PHP. I would like to give the user the option to sort the results by clicking on one of the various table headings. I know that I can sort them at the time that I query them, but this would require a new database query each time. I am thinking of making the heading a hyperlink similar to the following:

<a href=myresultspage.php?sort=price>
//this would be the link to sort by the price collumn.

I have managed to make a simple sorting function, by putting the results into an array then sorting the array by the appropriate dimension of the array as indicated by the value of $sort. My question is this:

If I keep the results in an array, how can I pass the array when the user clicks on the hyperlink that tells which collumn to sort by? Do I need to use session variables? It doesn't seem like I can pass an array as a GET variable.

Retrieving,Sorting & Displaying Multiple Results From Mutliple Tables
I need to know how to run a php / mysql query to do the following.

I have 1 database (lets call it "database" for now) within this database there are multiple tables ("News","Feature","Header_feature")

For NEWS I need only the 6 latest results pulled from that table and displayed in a table.  The "News" table has the following columns "ID","Title","Date","Body","Image"

For Feature I need only 1 result retrieved from the database and displayed under the variable $ticker as it will display as a scrolling marquee within a table.  The "Feature" table has the following columns "ID","Ticker".

For Header_feature I need only 1 result retrieved from the database and displayed in the following manner <a href="$link"><img src"$header_feature">[/url]  The "Header_feature table has the following columns "ID","image","link"

How would I code this all into 1 page?  I cant seem to get the query to do everything I want it to and display the results properly.  You can see what I have so far at www.getlivemedia.com  The $ticker is the scrolling text near the top of the page and the news is obviously the bulk of the page and $feature_image is the broken image.

Query Sorting
How would I have a query return only the top 3 or so entries based on a certain fields highest value? example,

entry 1 = 32
entry 2 = 21
entry 3 = 18
entry 4 = 41
entry 5 = 39
entry 6 = 22
entry 7 = 36

I would only want entries 4,5 and 7 to be returned. The top three out of the seven entries.

Sorting After Query
I have a db with intergers to hold "kills" & "deaths". This is for a game,.. now I have pulled my query ,. done my math,. and came to the number I want. Question is how would I sort it by the lowest number at this point? I need it sorted by "$tt" Code:

Sorting Query
I have the following sql table called "test"

id       title     order
1        test 1    1000
2        test 2    1001
3        test 3    1002

I then have a php page which lists all the above data, next to each row on my page, I have two buttons, one button which says "up" and one button which says "down".

Basically, what I want to do is, when the "up" button is clicked, switch the value in the "order" field with the next highest one, and if the "down" button is clicked, then it does the opposite.

For example, if the button "down" was selected on ID 2 on the above example table, then its `order` value "1001" would be swictched with the order value for ID 1, so the table would then look like

id       title     order
2        test 2    1000
1        test 1    1001
3        test 3    1002

And if the "up" button was selected on ID2, then the table would look like

id       title     order
1        test 1    1001
3        test 3    1001
2        test 2    1002

Does this make much sense?

I have tried to post the id value and its current `order` value and then doing the QUERY

$orderup = $_GET['order']+1;
$sql1 ="UPDATE `test` SET `order`='".$_GET['order']."' WHERE `order`='".$orderup."'";
@mysql_query($sql1, $connection) or die(mysql_error());

$sql ="UPDATE `test` SET `order`='".$orderup."' WHERE `id`='".$_GET['id']."'";
@mysql_query($sql, $connection) or die(mysql_error());

But that doesnt seem to work right.

MySQL Query Sorting
I was curious if there is a way to sort out duplicates in data returned by an query. I have a database, basically a mailing list database and when I query the database for the emails addresses, I get the returns echoed to the page as expected, but it looks like some people have signed up multiple times.

So I have duplicates in my echoed list.  Is there a way to have the data sort so the duplicates do not appear, and the email will only appear once on the list? I don't want people to be getting 5 of the same emails from me.

How Can I Tell Which Way My Database Is Sorting?
Ive got some mysql results,.. and I have wrote a simple script to sort them by column headers. Little link and url var to tell the sql which way to sort. My problem is how to I go about assigning ASC or DESC? Now that seemed real simple to me,. but then the question came up. How is it sorted in the first place?

If I could find out how it is sorted then it would be fairly simple to do an if statement to change the var in the ORDER BY clause. Anyone know how to tell which way the results are sorted to begin with?

Sorting Variables From Database
I have a function listed below, right now it sorts by $member_id I believe. I desire the same output ie.. member names, but I would like to sort it alphabetically by name. Is that possible? PHP Code:

Getting Too Many Results From A Query!
This is very peculiar -- for some reason, I'm getting 6-8 results from each
of these queries, although only one listing matches. I have a pair of forms
on one page:

<FORM>
Search for lastname: ____________ [Submit]
</FORM>
<FORM>
Search for email: ________________ [Submit]
</FORM>

This goes to a searchresults.php page:

if ($searchname !== "") {
$query="SELECT artistID,firstname,lastname,email,city,state,count ry
from artists WHERE lastname='$searchname'";
$result=mysql_query($query) or die(mysql_error("Could not execute
query."));
while($row = mysql_fetch_array($result)) {
$alt_artistID = $row['artistID'];
$alt_firstname = $row['firstname'];
$alt_lastname= $row['lastname'];
$alt_email = $row['email'];
$alt_city = $row['city'];
$alt_state = $row['state'];
$alt_country = $row['country'];
echo "<CENTER><HR>".$alt_artistID."<BR>"
.$alt_firstname." ".$alt_lastname."</A><BR>"
.$alt_email."<BR>"
.$alt_city.", ".$alt_state." ".$alt_country."<BR>
<A HREF=delete.php?aritstID=".$alt_artistID.">DELETE THIS
LISTING?</A><BR></CENTER>";
}
}

The second section is identical except for:
if ($searchemail !== "") {
$query="SELECT artistID,firstname,lastname,email,city,state,count ry
from artists WHERE email='$searchemail'";
etc...
}

I don't understand why I would get 6-8 records when you can look at them and
see that all but one clearly do not match...?

Using Query Results
Can you use a queries results only once? In this script I'm looping through a query and saving some values in an array. A little further through the script I need to use the same query for output. When I loop through nothing is echo'd to the browser. When I output a row count it shows that the correct number of records, so they must still be there.

Sorting Sql Results In An Array Using Things Outside The Array To Sort Them?
I'm using PHP to connect to a database full of place names, and their associated post codes, latitude and longitude on the earth. A user types his or her post code into a form, plus a distance (in miles), and the script looks for other area codes (first half of the post code) within that distance.

I can do that fine, but the results are ordered alphabetically by postcode, and I want to order it by the distance. Problem here, is that the distance isn't part of the array taken from the database, it takes the latitude and longitude of the area it's on in the while loop, and calculates the distance between the user's post code and that one, but it's not part of the array, so I can't sort the array using it.

How can I sort it? Can I add the calculated distances to the array, and sort it using sort()? If yes, how do I add them to the array?

Here's the page, just to explain better what the script does: http://navimaker.org/ed/owain/results.php?postcode=gl15&distance=34
Mess around with the postcode and distance vars.

I'd put the source on here too but I'm doing all this over SSH and can't copy & paste very easily .

Query Results In 2 Columns?
I'm struggling to figure out how to do this properly. I have done a mySQL
query to extract a list of names, and done a mysql_num_rows to determine how
many results I've gotten. I want to split the list in to two columns. I've
created $percol = $mysql_num_rows/2 but I'm not quite sure how to "loop"
through the first half of the list, echo </td><td> and then list the
balance. Can anyone give me some guidance on how best to structure this?

Finding The Results Of A Query
I am working on a script that will query a database for a FNAME/LNAME
combo. If it finds the combo, I need it to do one set of instructions.
If it doesn't find it, I need it to do something else. What I can't
figure out is what variable to check against. Here is what I have for
the relevant part of the script:

$connection = mysql_connect($hostname, $username, $password);
mysql_select_db($databasename) or die ("Cannot connect to database"
..mysql_error());
$query="SELECT FNAME, LNAME FROM (table) WHERE FNAME=('$FName') AND
NAME=('$LName')";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
mysql_close($connection);

I tried checking the value of $result to see if it changed depending on
whether or not it found the selection. It does not. I just can't figure
out what to use for:

if (some expression){
perform this code
}
else{
do this
}

Grouping Results Of Query
I'm brand new to PHP (just starting today to convert tons of
ColdFusion/Access code to PHP/MySQL). There is a function in
Coldfusion that I can't find an equivalent to in PHP. Here is
what I am trying to do:

If I have a query that results in this information:
State Firstname Lastname
Idaho Terry Pratchet
Vermont Dan Brown
Vermont Bob Smith
Virginia Alice Johnson
Virginia David Jones

I would like to output the info like this:

But all I can find in PHP is a way to loop through the query
and show every row... if you are familiar with Coldfusion,
what I am looking for is something similar to this:

<CFOUTPUT GROUP='State'>
#State#<BR>
<CFOUTPUT>
#Firstname# #Lastname#
</CFOUTPUT>
<BR>
</CFOUTPUT>

Is there a function that does this in PHP, or do I need to
write code that watches the value of 'State' and manually
takes care of things whenever it changes?

ODBC Query Results
Consider the following:

<?

$username = "foo";
$password = "bar";
$host = "db";

$connect = odbc_connect("$host", "$username", "$password") or die;

$query = "SELECT id, name, address, city, state, comments1, comments2
FROM data.table1, data.table2 WHERE id = ô˜'";

$result = odbc_exec($connect, $query);

while(odbc_fetch_row($result)){
$id = odbc_result($result, 1);
$name = odbc_result($result, 2);
$address = odbc_result($result, 3);
$city = odbc_result($result, 4);
$state = odbc_result($result, 5);
$zip = odbc_result($result, 6);
$comments1 = odbc_result($result, 7);
$comments2 = odbc_result($result, 8);
print("ID: $id<br>Name: $name<br>Address: $address<br>City:
$city<br>State: $state<br>Zip: $zip<br>Comments1:
$comments1<br>Comments2: $comments2<br>
");

}
?>

Only one record is returned from data.table1 (containing the id, name,
address, city, state, & zip). However, there are multiple records
returned from data.table2 (records from comments1 & comments2). What
is happening is that when I run this script, all of the data returned
from data.table1 is printed over & over again along with each record
returned from data.table2. How can I make it such that id, name,
address, city, state & zip are only printed once - and allow comments1
& comments2 to be printed multiple times for each occurance in the
database?

I've thought about just creating a second database query for the
records in data.table2, however I need the join I'm getting by using
the existing query.

For what it's worth, I'm connecting to a DB2 database using PHP /
Apache on Linux.

I'm confused by this.

Losing Query Results!
If I make a query;

$result = mysql_query($theQuery, $db);

and then make use of the query results like so;

while ($row = mysql_fetch_row($result)) {

//do something with query results}

I can't use $result again, I have to make another query! Why is this and is there any way around it?

Multiple Sql Query Results
I'm trying to do a query from 2 databases. Basically i have
catagories within 2 databases. If both catagories return 0 rows then it
does nothing but if one or both have rows returned then i need it to
echo a result. I guess where i'm wondering if there's an OR statement i
can use or something to that effect...

something like

if($numrows == 0 OR $numrows2 == 0) {
echo ('');
}else{
echo ('$result');



SQL Query - Results From Another PHP Page ?
Can I store this PHP code in another page, then refernece it on
multiple pages using Require or Include ???

//results from sql query
for ($i=0; $i<$number; $i++) {
$ID = mysql_result($result,$i,"ID");
$CompanyName = mysql_result($result,$i,"1");
$ContactName = mysql_result($result,$i,"2");
$Phone = mysql_result($result,$i,"3");
$HomePhone = mysql_result($result,$i,"4");
$MobilePhone = mysql_result($result,$i,"5");
$AltPhone = mysql_result($result,$i,"6");
$SecondContact = mysql_result($result,$i,"7");
$SecondPhone = mysql_result($result,$i,"8");
$ThirdContact = mysql_result($result,$i,"9");
$ThirdPhone = mysql_result($result,$i,"10");
$Notes = mysql_result($result,$i,"11")

Sql Query Results And Scrolling
I make a mySQL database query and display the first 10 results. Then
the user can click on "next" link to get the next 10 results. How can
I do that without issuing the sql query again? Can I keep the results
from the first query?

Query In PHP Won't Return Results In There's Only 1
$sql = 'SELECT `PageTitle` '
$sql .= 'FROM `Pages` '
$sql .= 'WHERE `PageID` = 1 LIMIT 0, 30'

I have run this query in MySQL control panel and it works perfectly.
When I try to do it via PHP I get no results.

If I select all rows (i.e I don't specify a "WHERE") I get one fewer
rows returned than there actually are.

Tabulating Sql Query Results
I'm trying to number my rows in the column named "Pos" but so far I not getting any success, someone please bail me out find below my script, this script displays my results fine but without my Positions (Pos); Code:

Combining Query Results
I have two queries which searches for any fixtures your clan (team) is in and then returns some information about the fixtures. Is there any way of combining these results and ordering them by date? Code:

Filtering Results With Php Query
This code works, but I don't know how to filter the results to where only one person is displayed..it displays all records with similar address or state or city, I would like to know how to make it display only one person when multiple search fields are entered.

I'm using PHP5, and I have searched the forums but I'm not sure exactly if I found what I'm looking for...I don't know much about php or mysql. Code:

Capturing/using Results Of Query
I would like to display/capture/use the URL's that are displayed on a web page after making a query to a forum.
What do I mean?

I am part of a forum that uses vBulletin.  One option is to display the forum topics that have had posts that day, i.e. active topics.

Essentially, when you click on the link:
http://www.somedomain.com/forum/search.php?do=getdaily

the resultant page has a list of the active topics, highlighted as links.

What i would like to do is capture/access that resultant page and use regular expressions to grab the URLs.  I can do the RegEx but I cannot seem to capture that resultant page.

How Do I Show Results Of A Query
I know how to connect to a Mysql table.  I want to run the query and show the results on my page.  I'll have about 25 different fields I need to show on the page.  Most of this information will be a couple of addresses. 

Basically, a billing and then a shipping address.  Can someone show me how to show some of this on a page?  I'll need to align all this stuff around the page. 

Filter Results Of Query
I am modifying some pages in CRE Loaded.

allprods.php list all currently active products and I added a manufacturers column that displays who makes that product.

I want to allow shoppers to filter the product list so that it shows only products from a particular manufacturer.

I have gone through several scenarios in my mind, but nothing I've thought of seems simple and bullet proof.

One of the issues is that the all products query includes all manufacturers.  If I were to put a variable in the query to select only a particular manufacturer, how would I code it so it does not interfere with the all products query?

Would logic based upon the value of a form action work?  If form action exists, someone wants to filter.  If not form action or form action = all, then they want the whole list. Seems like filtering a list is pretty common and there should be an easy solution.

Formatting Problem With Query Results
I have a minor problem with a script. I have written a piece of code (do...while loop) that will return results of a query a row at a time, with the proper formatting in a table. Everything works fine when there are results to lay out in the table. The problem arises when the query yields no results. When this happens, the loop below iterates once (without data) instead of not executing at all:

$result2=mysql_query("select * from ...) or die("");
$myrow2=mysql_fetch_array($result2);

do {

...bunch of stuff...

}

while($myrow2 = mysql_fetch_array($result2));


Where do we go from here?

Combining Results From MSQL Query
I have the following 2 queries which each produce a result. I have spent hours reading up and have searched devshed but I can't find how I would go about Adding these two numerical results together using PHP.

Query 1

$sql = "SELECT SUM(total) AS total_price FROM detail_tourdet WHERE voucher_id = '$voucher_id'";
$result = mysql_query ( $sql );
$row=mysql_fetch_array($result);
echo $row['total_price'];

Query 2

php $sql = "SELECT SUM(total) AS total_price FROM retail_acom WHERE voucher_id = '$voucher_id'";
$result = mysql_query ( $sql );
$row=mysql_fetch_array($result);
echo $row['total_price'];

How To LIMIT Results In Html Php/sql Query?
I need to limit results in the following query type:

http://www.somewhere.com/php/sql-a....ql_order=&pos=1

I found a reference that says I should be able to use LIMIT x[,y], but
I don't know where/exactly how to add that to the string. Once I know
what it's supposed to look like, and can write something to generate
it.

If someone could post an example using the above and limiting the
output to 100 records starting at position.

Display Query Results In A Table
$sql = "SELECT name FROM employee_tb;
$result_query = @mysql_query ($sql);// run the query
while ($row = mysql_fetch_array($result_query,MYSQL_NUM)){
$name = $row[0];}
// assuming i have 8 results

how can i display the results from this query in a table with 3 rows each column?

Query Results And Affected Rows?
I'm doing a mass database update and I have a query string something like this:

UPDATE table SET field1=0, field2='' WHERE (email='address1' OR email='address2' {and so on...} );

I know you can view how many rows were changed after its done. I'm wondering though, is there a way I can view which entries failed? For example, lets say the email address - 'address34' was not found in the database, is there anyway I can display this from this UPDATE query? or to do this, would I have to compare each address individually with the table to check if it exists? (and if it matters I have about 1000 adresses that are being updated from this)

Query Results With Multiple Keywords
The way I have it set up now, a form results in 2 keywords, namely Keyword and Keyword2 using 1 text field, and one select field. In the text field, the person enters in the City, in the Select field, they choose a state, which abbreviates it to 2 letters.
Now, for the code that is supposed to process this: Code:

Exploding Results Of Mysql Query
I have a table with times and dates listed like this:

0000-00-00 00:00:00
2003-09-20 20:26:22
etc
etc

What I want is to query the DB for the field (matchdate) and then get it to explode the ' ' to give jsut the date for me and then put it into a dropdown in a loop. this may sound easy but i too sleepy to work it out and searching aint good.

Sql Query Not Returning Correct Results
i'm using an entry in an sql database as a semaphore and it,
unfortunately, doesn't appear to be working. the script that spawns
the child processes has a for loop that performs the same basic sql
query over and over again until the value has changed (there's a one
second delay between each query). unfortunately, the resultant row is
always the same, even when the other process *has* changed it. as an
example, if the orig. value was of the entry was 0, and one second into
the execution of the second process, the entry was changed to 1, my
program would, even 10 seconds later, fetch 0. in other words, it'd
never be aware of the change.

any idea as to why this is and what i can do to fix it?

Aligning Multiple Query Results
I'm trying to pull data from 2 different tables and do a loop to
retrieve more than one row. I'm having problems with aligning the
information. Can someone lead me in the right direction? I've done some
looking myself and found something called GROUP BY? Is that what I need
to use?

Checking Lenth Of Query Results
If I return a result from a query with mysql_fetch_array and need to check the character length of a specific field, what is the best way? I have tried mysql_field_len but am getting errors with the code below: PHP Code:

Arrays, Query Results And Select Box
I want/need to pre-select a drop-down box with a value if it's present in both a lookup table and user account table. After wrestling with this for a few hours I give up.

i know this can't be this complicated, but apparently i'm missing something, so if anyone can suggest a way to go about this i'd be a little more sane. The idea is to have the user value already selected then when they change the value i'll update their account.

I Need To Export Query Results To A .txt File.
Here's some code:

I need this info displayed on a .txt file that is updated each time that text file is called up. So if a new result is added, when that text file is called up I need that new listing to appear there. Or every time a new result is added, it updates the text file. Whichever makes the most sense, I'm not sure.

How To Truncate Multiple Query Results....
I have a news section on my website, where the article(s) are stored in a MySQL database. Titles in one column, article body in another. On the actual page, I have a limited space to which to print the content, and need to truncate it so it does not overlap, or stretch the content div and blow the design out of whack.

When only returning one article from the db, I can do this easily, however, the problem is that not all articles are/will be lengthy enough to fill the div. In such cases, I want to return the next article, up to the remaining div space, then truncate it.

For example, right now, the article that's being displayed fills up more than the allotted space, so it's truncated. But the next three articles I post may be short, where I'd need all three plus a segment of a fourth to fill the space. Using Dreamweaver MX2k4 I can do this by "repeating that region", but limiting the number of characters is only applicable to each query, not to the overall div. As such, it won't work in the way I need. Code:


Copyright © 2005-08 www.BigResource.com, All rights reserved