2
votes

Im sure this is not to hard, but I cant seem to figure it out on my own.

I have a mysql db with a list of names, and im using the following to assembile the names into a comma seperated list.

$emailresult = mysql_query("SELECT * from leaddist")
        or die(mysql_error());
        while($row = mysql_fetch_array($emailresult)){
        $repemail .= $row['email'] . ", ";
        }
        echo $repemail;

this outputs something like: name1, name2, name3, name4, name5

my question is, what are some methods to shuffle that into: name3, name1, name4, name5, name2

then when executed again, it would be something like name 4, name1, name2, name5 and so on......

3
On a sidenote ... dont use the php legacy mysql connector ... use mysqli or PHP PDO instead - Terence

3 Answers

7
votes

You can use mysql for this:

SELECT * FROM `leaddist` ORDER BY RAND()

Note that this can be performance critical if the table is really large but should suite well for small to medium sized tables

1
votes

You could try to retrieve the SQL already randomized:

SELECT email
FROM leaddist
ORDER BY RAND()

Note: if you only need the email column, you should specify it in the query. Try to avoid the use of * in selects.

1
votes

You're going about it wrong. You're building a string. You should be building an array, then use the built-in PHP shuffle function:

$emails = array();
while($row = mysql_fetch_array($emailresult)){
    $emails[] = $row['email'];
}
shuffle($emails);

$repemail = implode(',', $emails);