user3678617
user3678617

Reputation: 21

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>";
}

Upvotes: 1

Views: 496

Answers (2)

AyB
AyB

Reputation: 11675

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.

Upvotes: 1

MisterBla
MisterBla

Reputation: 2395

Try using the shuffle() function.

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

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

    shuffle($row);

    // Write the data of the person
    echo "<dt>Sentence:</dt><dd>" . implode(' ', $row) . "</dd>";
}

Unrelated: mysql_* are deprecated as of php 5.5 and will be removed in the future. Use mysqli or PDO instead.

Upvotes: 1

Related Questions