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




PHP MySQL Order Results


I'm using:

  $sql = "SELECT * from $myTable ORDER BY `points` DESC LIMIT 5";
in a whileloop to display the top five scorers but would like to put their position next to the results (eg, 1, 2, 3, 4 and 5)

Is there an easy way to do this?




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
I Want To Alphabetize Results, ORDER BY Not Working...
I have a list of contacts I want spit out into a table... it does that fine, but I want to alphabetically order them by nickname in descending order... PHP Code:

ORDER BY MySQL
If you're dealing with ID #'s, or with numbers.. Make sure you are using INT instead of VARCHAR (which is probably obvious, but I had to find out the hard way). If you use INT you can sort the numbers correctly..

1
2
3
22
33

with VARCHAR you'll end up with

1
2
22
3
33

MySQL & PHP Order
I have a content page requesting data from MySQL. I have it working, however, not the way I want to. Whenever I add a new row to the tables, the new row adds, but BELOW all the rest of the rows. For example...

This is an existing row in a table 1
This is an existing row in a table 2
This is an existing row in a table 3
This is a NEW row that I just updated

I want it to be like this:
This is a NEW row that I just updated
This is an existing row in a table 3
This is an existing row in a table 2
This is an existing row in a table 1

This is the code I have for it currently: Code:

MySQL ORDER BY
I got my results to order the way I want. Which is
ORDER BY verified DESC
But after that I want to order another column in ascending order. I tried
ORDER BY verified DESC, device and that didn't work.

I also tried ORDER BY verified DESC ORDER BY device
Does anyone know how I can do this?

ORDER BY Problem (mySQL)
Is it possible to use two fields at the same time in an ORDER BY statement, using mySQL?

Let's say I have a table "user":

userId: int
userNick: varchar 255
userNickSpecial: varchar 255

Sometimes, I'd like to be able to sort the users using BOTH the "userNick" and "userNickSpecial"!

This:

SELECT * FROM user ORDER BY userNick, userNickSpecial;

will sort by userNick and then by userNickSpecial. I'd like the sort to be done on both fields at the same time!

Ex:
-----
userId: 1
userNick: 'bbb'
userNickSpecial: ''
-----
userId: 2
userNick: ''
userNickSpecial: 'ccc'
-----
userId: 3
userNick: ''
userNickSpecial: 'aaa'
-----
userId: 4
userNick: 'ddd'
userNickSpecial: ''
-----

Would sort the users like this:
userId: 3
userId: 1
userId: 2
userId: 4

Is it possible?

MySQL - Using Expressions In ORDER BY Statement
I am currently teaching myself PHP/MySQL to add functionality to a website showing event listings for an entertainment venue. The events in any day can run from 11am until 3am. I have a search script that will return all events by title, time, date and other criteria and users can click on any column heading in the results to sort by that column.

My problem is the event start time column. Sorting the data using "ORDER BY time" puts the post-midnight shows at the beginning of the list not the end.

Does anyone have any ideas as to how I could adapt the ORDER BY part of the SELECT statement to return the post-midnight shows at the end of the list.

I could presumably sort after deducting 4 hours off every time. Would something like ORDER BY (time-4) work (using simplistic shorthand for the "time-4")? I assume I would have to use the DATE_SUB() command but I am not sure about the format.

The time is currently recorded simply as hh:mm:ss in the MySQL database.

Selecting A Mysql Row Set In A Random Order
I have implemented a links bar on the side of a site, which I want to popuplate with links from a database randomly, but I feel the php workaround I used is inefficient.

Is there a way to randomize the result in a mysql SELECT query?
"SELECT * FROM links ORDER random"
I know the code above is probably way off, but it illustrates what I want I think.

Mysql Messes Up ORDER BY Optimisation?!
I have a pretty long query that ends with

ORDER BY R.r_recent_hits DESC LIMIT 0, 1

I also have an index on R.r_recent_hits. I did an explain select and
got this:

ALL - which means (from the manual):

A full table scan will be done for each combination of rows from the
previous tables. This is normally not good if the table is the first
table not marked const, and usually very bad in all other cases.

My question is, why in the world would MySql choose to do this type of
join when there is a perfectly good index there! And I have run analyse
on all of the tables.

It seems like it would be a no-brainer, as soon as the optimizer sees
ORDER BY, just use the given index for that column, that will get you
the highest value easily. Does any one know why it would not
automatically do that? The query essentially does nothing but selects
the highest value. If i suggest what index to use by saying USE INDEX,
it works fine. But, I don't think i should have to.

if you are interested, here is the query:

EXPLAIN SELECT H.accumulated_hits, R.num_messages, R.r_recent_hits,
T.topic_scope, R.thread_id, U.username, U.user_id, T.title,
UNIX_TIMESTAMP(T.post_time) AS post_time, T.topic_id, T.description FROM
threads as R, topics AS T , users AS U, hit_counter AS H WHERE
T.topic_id=R.topic_id AND H.object_type='THREAD' AND
H.object_id=R.thread_id AND U.user_id=T.user_id ORDER BY R.r_recent_hits
DESC LIMIT 0, 1

Search Results ($num_rows) Does Not Match $search Results (PHP,MySQL)?
For example, when I do a database search for a term I get 2 results but the $num_rows says there are 3 results.

I suspect it's because there are similar keywords within different search fields of the SQL statement. But I am stumped as to how I can change this. Any Suggestions? the code:

MySQL Results Not Working So Hot
Ok. Here I am again....probably posing a question with a solution so easy that, after looking at it for an hour, I can't figure out. Ok. here's the deal. please review the code below. Looks simple enough, right?

If/then Within MySQL Results List
I want to list job opportunities for a facility. If there are jobs in the database, I can list them without a problem. But if there are no jobs, I'd like to echo a line something like: "No jobs right now, come back later." But I can't get that line to echo. PHP Code:

Mysql Writing Results From 51 To 100
Can someone write me a mysql_query code which will get me results from 51 to 100 from $database?

Don't suggest me working with indexes, because i'm also deleting some rows (for example #1 is filled #2 is not, #3 is...)

Show Next Results Of MySQL DB
How do I get it so that php reads in the first 10 results out of a MySQL database. Then when Next or something is hit it displays the next 10 results and so on.

MySQL Results To Return Only One Value
For example, I have a column that has three different values, 1, 2, & 3. In the database, there may be over 500+ entries with one of these values assigned to it. How can I get MySQL to return just 1, 2, & 3 only once rather than several hundred times.

Hyperlinked MySQL Results W/PHP
I was wondering how results to db querys have attached links to each individual result? I have a good grasp of basic PHP & MySQL, but don't understand how that works. For example, if you have a db of products, all with individual id #, how do you get one product from the query a <ahref>? Could someone explain?

Compiling MySQL Results
Does anyone know how to compare multiple results from a MySQL query? For example, I would like to query the database and collect all the results into a variable (perhaps $totalresults). Then, I would like to use a single statement to compare each of the results within $totalresults to the statement's conditions.

Mysql: How Do I Get The Rowcount Of The Results?
I want to execute some alternate code if the a query produces zero results, but I can't find any info on the web about how to get the number of rows in a mysql result.

Getting Results From MySQL Database In PHP
I am trying to write a php page which connects to a MySQL
Database which is supposed to get the results from a table within a
database and display the results in a table.

Below is the code that I am using:

Limit Mysql Results
I have a script which has a mysql query which returns 20 results - I want to add some validation so if my variable ($var) is empty, it only allows the user to select the first 5 results my code is: -

$sql = mysql_query("SELECT * FROM greetingcards_cards WHERE category='$cat' LIMIT $from, $max_results");
while($row = mysql_fetch_array($sql)){   
        $image = $row['url'];
       $cardid = $row['cardid'];
        echo "<br><img src="$image" /><br><a href="?function=sendmessage&cardid=$cardid">Pick this card</a><br>";}

I want it so that if the variable is empty, instead of displaying "Pick this card" it displays - "You must register to pick this card" and have a different hyperlink Is this type of validation possible? if so how is it done?

Convert MySQL Results To XML
I just got Dreamweaver CS3, and I love the built in SPRY framework. It allows you to create web applications that use a table listing, and details listing very quickly. Unfortunately the only data the SPRY framework can accept is XML. Is there a built in function to convert from a $row result from MySQL to XML? Code:

Mysql Results - Ordering Them.
i need an mysql query to rank the results, like SELECT field FROM table and to order them greatest to least by the value of a different field. 

Mysql Results Pagination
I have a php code to split the results of a sql query over pages taht works great... But I need to add some feature, I need to add that if there are more than * pages it shows me "..." instead of the hole numbers of pages.. Code:

Sum All Of My MySQL Integer Results?
I have a bunch of rows, and for each row, the column "rating" has a number from 1-5. I need to add all of these together, so like if there were 3 rows with 5 for rating, it would return 15. If it's possible to do it with an SQL statement, I'll like it to average them.

Splitting MySQL Results
So I have a database, and I want to split the results into 2 columns. I don't want to alternate them, but have the first half in the left column, and the second half in the right column. How can I handle this so that it does it automatically no matter what number of entries (and so that if it's an odd number, the one overflow is on the left).

MySQL Multiple Tables / Results
I would like to perform multiple queries to a MySQL database and have all
the results in 1 result set.

Parsing PHP Code In MySQL Results Set?
I have a PHP script that pulls content from an MySQL database and returns a result set.

Is there a way I can put PHP code within a field in the database and have that code parsed as PHP code on returning a results set? If possible, I want just one field of the database parsed for PHP code. The results set is return as a straight result, not within a loop. Just inserting the <? PHP code thus ?> returns that as sources code not parsed.

Populating Array With Mysql Results
I'm returning a result set of one field in a table, and want to populate an array with the results. I can't for the life of me figure out a simple way to do this without using mysql_fetch_array() to cycle through the results, append that to a var, then explode that into a var and pass that. PHP Code:

MySql - Outputting Results In Groups
I want to output mysql data by groups (states). However each time php/mysql comes to a new state in the results I want it to print the state name before putting the results. Does php have some sort of memory function to recognize when the state has changed?

Split Mysql Results Into Two Columns
Trying to develop php catalog, but can't split the results into two columns, PHPcode:        

Mysql Results Output Problem
I trying to set up some subdomains and I'm at the early stages of just testing the the thing . I have set up a small test DB, with the following fields, company, id, url.

I have also set up a test page to see if the output corresponds with the subdomain name. If the domain exists the result with echo "domain exists" if not it will output "does not exist". But the page just says "does not exist" all the time even though the domains are set up.here's the 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.

Store Mysql Results Into An Array
i just started using php. i've used it before as a maintainer. fun stuff. well now i'm the writer. i want to abstract all the DB commands away from myself and all other developers. so i'm writing a function to query the php database from all users of the database and store them into an array as a return value so that i can seperate my database code from my html creation code.

1. is there a way to put all my database functions into a php file and include that file into all my other php pages? similiarly to a #include in C++ or a import package name in Java?

2. my code to run down the fetched results and store them into an array doesn't seem to be working the way i want it to. if i print out the results from the mysql returned fetch the data is fine. however the array seems to print out "Array[elementnumber]" instead of the value. Code:

Mysql Results <-- Previous Row, And Next Row, Showing Next Ok
I query a database and return a result on the column "reference".
There might be 7 listings. Each row is displayed in a table, with
links through to a detail page. I am working on having a "previous"
record and a "next" record link on the detail page.

This code below works, for the "next" record, by searching the values
in the array $myarray for the variable $ref. It then returns the key
value and the key value, as a number, is deducted by one and plus'd by
one to give me the previous row and the next row.

Returning the value of the next row works a treat, but for some reason
the previous row, deduct 1, while it echoes a value to screen, doesn't
work.

This is the code:

(query database and then:)
//$ref is a variable carried into the page

$num_rows = mysql_num_rows($result2);

$i=0;
while ($i < $num_rows) {
$next=mysql_result($result2,$i,"reference");

++$i;

$myarray = array("$i"=>"$next");
foreach($myarray as $key=>$value) {
if ($value == "$ref"){

$b=($key);
$c=($key+1);
$a=($key-1);

}}

if ($a == "0") {
echo "No Preceding Record";

} else {
if ($key == "$a") echo "<a
href=../detail/index.php?name=$value>Previous Record</a>";
}

if ($key == "$b") echo "This is the current Record";

if ($num_rows < $c) {
echo "Records End";
} else {
if ($key == "$c") echo "<a href=../detail/index.php?name=$value>Next
Record</a>";
}
}

} else {

JOIN Table Results W/MySQL
I have a query with a simple JOIN.

For example:

SELECT * FROM Companies
INNER JOIN CompanyTypes ON Companies.CompanyID = CompanyTypes.CompanyID

The query returns all fields from both Companies AND CompanyTypes. I would
like all fields from Companies only.

Counting Results From A Mysql Database
I want to know how many results throw a query in order to know if they have reached a limit.I.E.

$sql = mysql_query ("select * from classifieds where user='$username'");
while ($row = mysql_fetch_array($sql)){}

I want to check lets say that only 10 classifieds per  'username' can be created. If ten or more classifieds are in the database for that 'username' then show error message.

Alternating Row Colors With MySQL Results
Is there any way i could make a image for the alternating row colors instead of a strait bold color, for instance:

$color1 = "#CCFFCC";
$color2 = "#BFD8BC";

Would there be anyway to link an image in there? I have tried it this way:

$color1 = "<img src='..style1.jpg'>";
$color2 = "<img src='..style2.jpg'>";

How Can I Arrange Results Alphabetically In MySQL
I am using this code to retrieve names from the databse

$q = "SELECT * FROM
names
ORDER BY date DESC
LIMIT 5;";

How can i arrange names alphabetically

MySQL Query Not Returning All Results
I have a user table in the DB, for example:

+---------+----------------+-------------------+
|     uid     |     username     |       firstname       |
|----------+----------------+------------------+
|       1     |       cobby        |       Andrew          |
|       2     |       admini        |     test-account    |
+---------+-----------------+------------------+

If, in phpMyAdmin, I query:
   SELECT `username` FROM `users`;

It will return results correctly (cobby and admini, respectively).
But if I make a simple PHP script, such as:

<?php

mysql_connect('localhost', 'cobby', 'dbpass');
mysql_select_db('testdb');

$query  = mysql_query('SELECT `username` FROM `users`');
print_r(mysql_fetch_assoc($query));

?>

It only returns:
Array ( [username] => admini )

Why does it only return the second result? I have a feeling I'm doing something really silly, but I looked over this test script and its got me stumped.

Mysql Dump Results In Blankfile
I am trying to get my script working to back up a mysql database. Everything works fine only the output results in a blank file. Code:

Merging Results From Two Mysql Databases
I have made two websites on seperate servers both with a database of their own.
They are identical but with different results in the databases. I want to make a page on one of the sites that will merge the information from both databases.

e.g.
site 1 has a list in date order
site 2 has a list in date order

I want site 1 to have the list merged together to form one big list but still be in date order. Also I want to be able to have the results of site 2 in a different font colour to site 1.

i.e.
Site 1 results

10th jan - something
15th jan - something else
19th jan - more

Site 2 results

11th jan - even more
13th jan - some more
16th jan - more stuff

Merged page

10th jan - something
11th jan - even more
13th jan - some more
15th jan - something else
16th jan - more stuff
19th jan - more

can anyone help with this?

Using Arrays With Mysql Query Results
im currently in the process of making a piece of code that will firstly take all the data from a table in mysql and then assign it to an array. This data will consist of several different rows of data each with different infomation for each field in the table.

i want to be able to use an array in a loop so that depending on which number of the loop is on will change the infomation that is assigned to a certain array. Code:

Displaying MySQL Results As URLs
I'm attempting to turn the results of a query into urls, yet I keep getting this error, "Parse error: syntax error, unexpected '<' in staff.php on line 190." I've coded and recoded this, yet for some reason I cannot get this error to go away. I know it's probably simple, but what am I missing? Code:

Presenting MySQL Results In A Paged Format.
I am developing a classified ad script using php4 and MySQL. My problem is: I want to display only 10 results of a dB search on each page.

At the botton of the page, I'd like to add forward and back links so that people can go forwards and backwards through the search results, with each page showing 10 results.

Can anyone point me towards a pre-existing script or example I can learn from?

Displaying X Number Of MySQL Results Per Page
I'm writing a search on a MySQL DB, and everything so far has just gone swimmingly. I've got a "results per page" drop down box in my form, with a few different values.

At the moment, I'm just using:

while($myrow = mysql_fetch_array($result)

to output results to screen.

I'm not too sure how to go about it, but I did have two thoughts:

1) Suck the results into a multi-dimensional array, and pass the array to a display results script (not sure if you can pass arrays to other scripts???

2) Display x number of results, then have the "Next" (or 2, 3... ) links call the search again, but displaying results x+1 - x+x.

1 sounds like too much trouble, and 2 sounds inefficient. Not too sure how else to go about it. Any info / thoughts you guys have would be much appreciated.

On a side note, how do you look at a specific row in the result?

Possible To Create A Variable From The Results Of A Mysql Query?
I need to perform a mysql query,Take the results and create a loop for each item that returns, and then create a variable that will pull the complete results from the query to include into a template. here is the code I am woring with PHP Code:

Caching MySQL Search Query & Results
I'm developing a site that may eventually have a very large database of
users (hopefully, but who knows). It will be a community website where
users can search each other (think Friendster, Classmates, every dating site
out there, etc.).

Often there will be queries with multiple joins and sometimes may include a
few fulltext searches. Each page of results will have a limited number of
results displayed (obviously). As I understand it, MySQL caches only exact
queries, so doing a LIMIT (x,y) on each query to get results for the
specific page will cause MySQL to run the entire query again, instead of
pulling from the cache. I will limit the results to 1000, but what's the
best way to limit results per page?

I was thinking that I could run the SELECT and LIMIT to 1000, then do a
mysql_data_seek to jump to the starting row for the page and fetch a certain
number of rows for the page. For each page, the exact same SELECT would be
used and therefore the results would be cached.

Also, how should I save the search query? The users will be searching with
any number of search terms, way too many to do use GET variables. I don't
want to create a hidden form with each search term as hidden inputs (for
one, that's kind of lame). I was thinking of saving the search query to the
database, I guess I could implode the POST array into a string and then save
it in the db.

Mysql Doesnt Return All Results Of A Query
I have an sql query like this:
SELECT column FROM table WHERE column1="3" AND column2="1"
This query works perfectly if i run it in the command line, to be
exactly it return two results.
But if i run it from php i just get the first of the two results.
Any ideas?

Mysql 4.1.8
php 5.0.3

I have a second problem. But its more of a question.
if i run the foreach loop on an array like this
array("id" => "78"), then it splits 78 up in 7 and 8.
Now you say its stupid to use a foreach for this array. But in the
function there i use it the array could also be two dimensional.
Is this behavior normal? I looked in the php manual but found nothing.

Show Mysql Query Results On Pages
Does anyone have a script that will show mysql query results as paged results? This is what I have at the moment and it does not pass the results to the second page. Code:

How To Pass Mysql Search Results From One Page To Another
I am creating a website that uses PHP to query a MySql database. upon supplying the PHP script with a given search string and search term, a list of scientific documents with attributes such as author, date, url and revision are returned. Each document also has a unique id number within the database. What I would like to do is create a system whereby user of the site can leave reviews for each particular document, much like the product review system employed at jungle.com. I have got to the stage where the php script outputs a list of results each separated by a horizontal rule and what i would like is to be able to place a button on each record marked submit review, which would then take the user to a form where he or she could leave a review which would placed into a reviews table in the database.

However my problem is that i do not understand how to pass the paper id automatically to the form such that the user does not have the inconvenience of having to type into the form. Does anyone have any ideas on how I could solve this problem?


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