dongmu6578 2012-10-01 11:51
浏览 18
已采纳

PHP SQL - 随机选择1行,其中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.

  • 写回答

2条回答 默认 最新

  • douhui3305 2012-10-01 11:56
    关注
    $query = "SELECT * FROM $usertable
              WHERE region IN ('UK','YK')          
              ORDER BY RAND() LIMIT 1";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改