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*

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.