1

I have a MySQL table with four columns, submited_name, submited_URL, submited_type, uniqueID. In this table i have about 1000 records. I need to select 10 random entries. The problem is that I need to split selected random values into separate PHP arrays. One for each column. My arrays should look something like this:

$ten_random_names = array ('name26', 'name55', 'name107', ect.);
$ten_random_URL = array ('url for name26', 'url for name55', 'url for name107', ect..);
$ten_random_types = array ('type for name26', 'type for name55', 'type for name107', ect..);
2

2 Answers 2

5

The basics:

$sql = "SELECT name, url, type FROM ... WHERE ... ORDER BY random() LIMIT 10"; // inefficient, but works
$results = mysql_query($sql) or die(mysql_error());

$names = $url = $types = array();
while($row = mysql_fetch_assoc($results)) {
   $names[] = $row['name'];
   $url[] = $row['url'];
   $type[] = $row['type'];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Shouldn't you add LIMIT 10 in the query?
2
$query = "SELECT *
          FROM tablename
          ORDER BY RAND()
          LIMIT 10";
$result = mysql_query($query);

$ten_random_names = $ten_random_URL = $ten_random_types = array();
while ($row = mysql_fetch_assoc($result)) {
  $ten_random_names[] = $row['submited_name'];
  $ten_random_URL[] = $row['submited_URL'];
  $ten_random_types[] = $row['submited_type'];
}

1 Comment

The mysql extension is outdated and on its way to deprecation. New code should use mysqli or PDO, both of which have important advantages, such as support for prepared statements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.