Jump to content

[SOLVED] Placing SQL Rows into an array and picking one at random


Dale_G

Recommended Posts

Yeah, anyone know how to do this?

 

At first I thought it would be like this

 

In this example, we are querying a database named 'ibf_members', two columns are named 'id' and 'member_name', and here we're trying to get all the member id's place them into an array, and pick what out at random using the rand function.

 

	$result = mysql_query( "SELECT * FROM ibf_members" );

	$myArray = array();
	while ( $row = mysql_fetch_array( $result ) )
	{
		$myArray[] = $row['id'];
	}

	$rows = count( $myArray );
	$id = rand( 1, $rows );
	$id = $myArray[$id];

	$idresult = mysql_query( "SELECT * from ibf_members WHERE id = '$id'" );

	$membername = mysql_result( $idresult , 0, "member_name" );

	$message = '<b>Member Name:</b> '.$message;

 

And, we're not having much luck here with this one, since an array starts at 0, for SOME reason it seems 0 is being picked occasionally at random, and id 0 does not exist in the database since the PRIMARY KEY starts at 1.

 

So, this method isn't working too well. Anyone care to share there methods with SQL and arrays? *I rarely use SQL, just getting into it now*

Your doing it the HARD way.

 

<?php

$result = mysql_query( "SELECT * FROM ibf_members ORDER BY RAND() LIMIT 1");
$row = mysql_fetch_assoc($result);

$message = '<b>Member Name:</b>  '.$row['member_name'];

Your doing it the HARD way.

 

<?php

$result = mysql_query( "SELECT * FROM ibf_members ORDER BY RAND() LIMIT 1");
$row = mysql_fetch_assoc($result);

$message = '<b>Member Name:</b>  '.$row['member_name'];

 

Thanks! That did the trick.

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.