Randomly sort php array - php

I am getting an array of 25 items from a database using SQL. I want to take 16 of the items and random to use. I thought if I could randomly sort the array I could then take the first 16 items.
Is there a way to randomly sort an array in php, or perform an SQL SELECT that returns to results in a random order?

You can do this in SQL:
<your select here>
order by rand()
limit 16;

Related

paginating random list sql

Im working in a basic pagination list where I need all the results be retrieved ramdomly
this is why I use
SELECT *
FROM table
WHERE 1
ORDER BY rand()
It works well until I need to paginate it...
SELECT *
FROM table
WHERE 1
ORDER BY rand()
LIMIT $offset, $recordsperPage
How do I retrieve the whole list in random order, but when paginated, every page do not repeat the prior random words?
If you provide a consistent seed to the rand() call, you'll get the same sequence. You might use something derived from the date, for example, to give the same results for the day, or generate some other random seed from PHP and save it in the session, to give the same results only for a given visitor.

mysql_fetch_array() and output in chunks

So I have a table with 45 records (but can be dynamic) and I use mysql_fetch_array() to get the data from the database. What is the best way to output 5 records at a time? So I need to do record 1-5, then have a link for records 6-10, 11-15, and so on. I thought about doing something with array_chunk but not sure how to keep track of the record number. Thanks for hints.
To get the first 5 results form a table:
SELECT * FROM table ORDER BY table.column_name ASC LIMIT 0, 5
Selects from `table`
Ordered by the column name Ascending
Limit 0,5 selects the first 5 results, starting at 0.
Change LIMIT 0,5 to 5,5 to list results 6-10 (start at record 5, and continue for 5 records.)
Ordering is just good practice to ensure consistency. Under most circumstances set this to 'id' if you have an auto-increment 'id' column. If you want results sorted by date, order by a timestamp column. If you want data reversed, order by DESC.
You can keep track of where your queries are though PHP Sessions, Passing GET parameters, temporary database tables, and probably a few more I missed.
Other solution:
Use the array returned from the mysql_fetch_array() and utilite http://php.net/manual/en/language.types.array.php
The obvious disadvantage to this approach is the fact that it fetches all rows in the table. This is okay if you'll NEVER have more than a manageable number of rows. In your case, 45 should be fine, assuming they're not gigantic rows. This approach may also may useful if you want data pre-loaded.
I'd suggest using limits and incremental offsets in your query. Your first query would then be:
select * from TABLE limit 0,5;
Your link has a parameter referencing the next offset so the next query would be:
select * from TABLE limit 5,5;
And so on.
You need in your query LIMIT 0,5. Search web for php paginator.

How to sort selected rows (truly) randomly?

Currently, I am using this query in my PHP script:
SELECT * FROM `ebooks` WHERE `id`!=$ebook[id] ORDER BY RAND() LIMIT 125;
The database will be about 2500 rows big at max, but I've read that ORDER BY RAND() eventually will slow down the processing time as the data in the database grows.
So I am looking for an alternate method for my query to make things still run smoothly.
Also, I noticed that ORDER BY RAND() is not truly randomizing the rows, because often I see that it follows some kind of pattern that sometimes repeats over and over again.
Is there any method to truly randomize the rows?
The RAND() function is a pseudo-random number generator and if you do not initialize it with different values will give you the same sequence of numbers, so what you should do is:
SELECT * FROM `ebooks` WHERE `id`!=$ebook[id] ORDER BY RAND(UNIX_TIMESTAMP()) LIMIT 125;
which will seed the random number generator from the current time and will give you a different sequence of numbers.
RAND() will slow down the SELECT's ORDER BY clause since it has to generate a random number every time and then sort by it. I would suggest you have the data returned to the calling program and randomize it there using something like array_rand.
This question has already been answered:
quick selection of a random row from a large table in mysql
Here too:
http://snippetsofcode.wordpress.com/2011/08/01/fast-php-mysql-random-rows/

Sort data using sort function or sort as retrieved from database?

I have a list of teams with corresponding scores.
$name[$i] contains the names while scores[$i] contains the corresponding scores
I need to sort the teams by score while maintaining a scores association with it's corresponding team name.
I am wondering is it best to create a multidimensional array such as
$teaminfo[$name][$score] and use a sort function or am I better off
sorting the data as it is grabbed from the database using sql?
Does it even matter which way? I am looking for the simplest way.
You'll save yourself a whole world of headaches by sorting it direct from the database. Just include a ORDER BY clause in your SQL.
EDIT:
If currently running 2 queries then
SELECT first_table.*, second_table.* WHERE first_table.id = second_table.id
ORDER BY second_table.score DESC
(or whatever!)
Just to expand on Josh's answer....
I need to sort the teams by score...a multidimensional array such as $teaminfo[$name][$score]
WTF? If a team can only have one score why try to keep a single value in an array? You only need a simple array (BTW: PHP arrays aren't multi-dimensional - they're nested):
$s=mysql_query("SELECT team, score FROM yourtable");
while($r=mysql_fetch_assoc($s)) {
$data[$r['team']]=$r['score'];
}
arsort($data);
However it will be much faster to sort the data in the database before returning it to PHP. OTOH it's possible that you may have multiple values for $score for each $team - and we don't know how these are combined to determine order - by max value? by average? total? something else? In which case you may need a subquery.

shuffling from an array with mysql

I need some help here.
I have a mysql table called dictionary like this:
id word
1 test
2 hello
4 bye
7 werd
In php, I want to query the db so that I can get an array of the id field
so the array would list 1 2 4 7.
With this array, I want to run the array_rand function in php so I can get a random number from 1 2 4 7.
Can someone show me the proper mysql query to list the id field and return it into php as an array?
and how I could run that array with random array function.
No need shuffle this in php, - effective is to
use "SELECT id FROM table ORDER BY rand();"
than take all records and store id into array ...
Use the shuffle function
If you plan on using the random row and then querying for another, I would just randomize on the MySQL query. Get a count of the rows in the table, create a random integer somewhere between 0 and that count, and then use LIMIT in your MySQL query to return a random row.
If you plan on keeping it all in memory, then David's answer would work better.

Categories