Henry Aspden
Henry Aspden

Reputation: 1945

PHP SQL - Random Select 1 Row, Where ID = x

I have a MySQL database and I need a PHP to pull a random row. I have successfully created

$query = "SELECT * FROM $usertable
          WHERE region='UK'          
          ORDER BY RAND() LIMIT 1";

This successfully randomly pulls a row; however, it is not limited to where region=2.

I need to be able to:

  1. pull randomly when region=UK
  2. pull randomly when region=UK or ##

(where ## is actually another region, for example, YK = Yorkshire)

Basically I need it to select rows randomly but ONLY when region=UK.

region is a label for one of my fields/collumns, and UK is the content of the VARCHAR in that for a number of rows.

I have the rest of the code sorted.

I have a simple database and the php as follows:

<?php
//Sample Database Connection Syntax for PHP and MySQL.
//Connect To Database
$hostname="carbonmarketing.db.9606426.hostedresource.com";
$username="MarketReadOnly";
$password="Read0nly1";
$dbname="carbonmarketing";
$usertable="ClientList";
$advertfooter = "advertfooter";
mysql_connect($hostname,$username, $password) or die ("<html>%MINIFYHTML4333ddb1f6ba50276851b9f9854a5c817%</html>");
mysql_select_db($dbname);
# Check If Record Exists
$query = "SELECT * FROM $usertable
          WHERE region='UK'          
          ORDER BY RAND() LIMIT 1";
$result = mysql_query($query);
if($result)
{
    while($row = mysql_fetch_array($result))
    {
        $advertfooter = $row["$advertfooter"];
        echo "$advertfooter";

    }
}
?>

But, it's just pulling randomly for all values of the region column

Let me know if it would help for you to see the database.

Upvotes: 0

Views: 1987

Answers (2)

Mihai Iorga
Mihai Iorga

Reputation: 39704

Make and array with your regions and implode them:

$region = array('UK', 'YK');
$implode = implode("', '", $region);
$query = "SELECT * FROM `".$usertable."` WHERE `region` IN ('".$implode."') ORDER BY RAND() LIMIT 1";

Upvotes: 2

Riz
Riz

Reputation: 10246

$query = "SELECT * FROM $usertable
          WHERE region IN ('UK','YK')          
          ORDER BY RAND() LIMIT 1";

Upvotes: 1

Related Questions