Search code examples
phprandomphpmyadminshufflescramble

How to randomize the columns in a selected row in PHP


The selected id will select the row and randomize. However, it could randomize the same elements. For example: 'I like to play the piano.' The output I'm expecting is randomized to eg. ' Play the like to I piano ' But what I receives sometimes turns out to be ' I piano piano like to piano' This words comes from the database(phpmyadmin). How do I make it such that the data will all appear but not repeat?

$strSQL = "SELECT * FROM sentences WHERE id 
ORDER BY RAND() LIMIT 1;";

$x = rand(1,4);
echo "$x";
$y = rand(1,4);
echo "$y";
$z = rand(1,4);
echo "$z";
$c = rand(1,4);
echo "$c";

$rs = mysql_query($strSQL);

// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {

    // Write the data of the person
    echo "<dt>Sentence:</dt><dd>" . $row["$x"] . " " . $row["$y"] . " " . $row["$z"] . " " . $row["$c"] ."</dd>";
}

Solution

  • You can do:

    //create an array with numbers 1-4
    $order = array(1,2,3,4);
    
    //shuffle them in random order
    shuffle($order);
    
    $rs = mysql_query($strSQL);
    
    // Loop the recordset $rs
    while($row = mysql_fetch_array($rs)) {
        // Write the data of the person
        //Display all the array values from 0-3 (array index starts from 0)
        echo "<dt>Sentence:</dt><dd>" . $row[$order[0]] . " " . $row[$order[1]] . " " . $row[$order[2]] . " " . $row[$order[3]] ."</dd>";
    }
    

    Note:

    Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.