Jump to content

[SOLVED] PHP MySQL - display random results?


simonp

Recommended Posts

Hello,

 

I'm using this code to display the first 8 results from a query but would like to be able to show 8 random results instead - is this possible?

 

Cheers

 

Simon

 

<?php

//get stuff from db

  // Make the connection
  $db = mysql_connect($myHost, $myUser, $myPass);

  // Select the database
  mysql_select_db($myDB,$db);

  $sql = "SELECT * from $myTable";

  // Get the query object
  @$result=mysql_query($sql,$db);

  // How many rows?
  $numRows = mysql_num_rows($result);

  // Initialise output
  $output = '';

  //for($i=0; $i<$numRows; $i++){
  for($i=0; $i<8; $i++){
$row = mysql_fetch_array($result);
$output .= '<TD>user=' . $row['user'] . 'victim=' . $row['victim'] . '</TD>'; etc
                              }

  // Close the database  connection
  mysql_close($db);

Link to comment
https://forums.phpfreaks.com/topic/78541-solved-php-mysql-display-random-results/
Share on other sites

You can do it all with the mysql query, and use a foreach loop:

 

<?php

//get stuff from db

  // Make the connection
  $db = mysql_connect($myHost, $myUser, $myPass);

  // Select the database
  mysql_select_db($myDB,$db);

  $sql = "SELECT * from $myTable ORDER BY RAND() LIMIT 8";

  // Get the query object
  @$result=mysql_query($sql,$db);

  // How many rows?
  $numRows = mysql_num_rows($result);

  // Initialise output
  $output = '';


  foreach($row as mysql_fetch_assoc($result)){
	$output .= '<TD>user=' . $row['user'] . 'victim=' . $row['victim'] . '</TD>'; etc
  }

  // Close the database  connection
  mysql_close($db);

 

 

Hi again,

 

Thanks for that - I keep getting an error though and can't see what I've missed:

 

Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE or '$'

 

on the foreach line . . .

 

I've tried moving things about but can't make it work - any suggestions!?

 

Cheers

 

Simon

 

 

Corr, i'd love to know what i was thinking when i posted that code. It needs to be a while loop:

 

<?php

//get stuff from db

  // Make the connection
  $db = mysql_connect($myHost, $myUser, $myPass);

  // Select the database
  mysql_select_db($myDB,$db);

  $sql = "SELECT * from $myTable ORDER BY RAND() LIMIT 8";

  // Get the query object
  @$result=mysql_query($sql,$db);

  // How many rows?
  $numRows = mysql_num_rows($result);

  // Initialise output
  $output = '';


while($row = mysql_fetch_assoc($result)){
	$output .= '<TD>user=' . $row['user'] . 'victim=' . $row['victim'] . '</TD>'; etc
  }

  // Close the database  connection
  mysql_close($db);

 

In my defence, i do have a cold :P

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.