Jump to content

Select Random id from table to link


starvinmarvin14

Recommended Posts

I'm trying to select a random id from a table called 'image'. I want the id number to be at the end of a link such as view.php?id=123. Here is my code:

 

$query=mysql_query("SELECT id FROM image WHERE active='yes' ORDER BY RAND() LIMIT 1");

 

echo <<<OPT

<meta http-equiv="REFRESH" content="0;url=http://www.mysite.com/view.php?id={$query}">

OPT;

 

It does not display the number in the link. What have i done wrong?

Link to comment
https://forums.phpfreaks.com/topic/253132-select-random-id-from-table-to-link/
Share on other sites

$query=mysql_query("SELECT id FROM image WHERE active='yes' ORDER BY RAND() LIMIT 1");

$query_result = mysql_result($query,0);

 

echo <<<OPT

<meta http-equiv="REFRESH" content="0;url=http://www.mysite.com/view.php?id={$query_result}">

OPT;

 

Tried that and got this...

 

"Warning: mysql_result(): supplied argument is not a valid MySQL result resource in /home/.../public_html/.../random.php on line 9"

it seems like your query is not returning any rows, try to do this

 

if(mysql_num_rows($query)){
$query_result = mysql_result($query,0);
echo <<<OPT
   <meta http-equiv="REFRESH" content="0;url=http://www.mysite.com/view.php?id={$query_result}">
OPT;
}else{
echo 'no records found';
}

Tried this...

 

$query = mysql_query("SELECT id FROM image WHERE active='yes' ORDER BY RAND() LIMIT 1");

if(mysql_num_rows($query)){

$query_result = mysql_result($query,0);

 

 

echo <<<OPT

<meta http-equiv="REFRESH" content="0;url=http://www.mysite.com/view.php?id={$query_result}">

OPT;

}else{

echo 'no records found';

}

 

 

Now I am getting this error...

 

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/.../public_html/.../random.php on line 9

no records found

 

I only have to rows at the moment with the id 18 and 19. How would i use mysqli_error()?

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

$id = $row['id'];

 

 

echo <<<OPT

<meta http-equiv="REFRESH" content="0;url=http://www.mysite.com/view.php?id={$id}">

OPT;

 

echo $row

 

When i echo the row I get "Resource id #2" every time.

$row holds the result resource returned by mysql_query. You'll need to use one of the mysql_fetch_* functions, such as mysql_fetch_assoc to extract the data from the result resource.

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.