-1

What I am trying to do is: I have a table called Stations, and it has 100 columns. I want to select all records from Stations and randomly select 1 record and echo the random record.

Here is what I have got so far:

<?PHP

$connect = mysql_connect("***", "****", "****") or  die("Connection Failed");
mysql_select_db("***");
$query = mysql_query("SELECT * FROM Stations ORDER BY RAND() LIMIT 1");

WHILE($rows = mysql_fetch_array($query)):

$Station = $rows['Station1'];///seems it will only show Station1 Column I have Station1 to Station100 was not sure how to add rest of Stations

endwhile;
?>
Julian
  • 361
  • 1
  • 4
  • 18
user3015877
  • 33
  • 1
  • 7

1 Answers1

0

Since you're limiting the result set to only one row, you don't need that while() loop. Just fetch the row from the result set and use it afterwards, like this:

$rows = mysql_fetch_array($query);

Now comes to your question,

... it will only show Station1 Column I have Station1 to Station100 was not sure how to add rest of Stations

To display all hundred column values, it's better to use a for loop like this,

for($i = 1; $i <= 100; ++$i){
    // display $rows['Station' . $i] as per your choice. Below is one way.
    echo $rows['Station' . $i] . '<br />';
}

Update:

From your comment,

... I need it to randomly choose 1 value out of all 100 columns and echo that value please

After fetching the row from the result set, use array_rand() function to get a random key out of the array, and then use that key to display the column value, like this:

$randKey = array_rand($rows);
echo $rows[$randKey];

Sidenote: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or PDO extensions instead. Also read, why shouldn't I use mysql_* functions in PHP?.

Community
  • 1
  • 1
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
  • Thanks for everyones help, Rajdeep i have used your code above and it shows all my column data. what i need it to do is all my columns have 1 row with a name in it. I need it to randomly choose 1 value out of all 100 columns and echo that value please – user3015877 Dec 10 '16 at 19:41
  • @user3015877 I've updated my answer, please see the **Update** section of my answer. – Rajdeep Paul Dec 10 '16 at 19:49
  • Rajdeep, Thanks for the help, that did the trick, appreciate very much. – user3015877 Dec 10 '16 at 19:55