PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 20, 2022

[FIXED] How to randomize the columns in a selected row in PHP

 February 20, 2022     php, phpmyadmin, random, scramble, shuffle     No comments   

Issue

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.



Answered By - AyB
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing