0

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.

1
  • I am new to PHP and SQL and moving to fast (running before I can walk haha) Commented Oct 1, 2012 at 11:55

2 Answers 2

2

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";
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

ahh I tried this method but as $query = "SELECT * FROM $usertable WHERE region IN (UK, YK) ORDER BY RAND() LIMIT 1";
You forgot single quotes around region names.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.