简体   繁体   中英

How to select only 1 row from a query result? like the 4th row

I have this code and am looking to make a sort of "quotes area" on my website. I want it to select 3 random quotes from my database everytime. I know about the function rand(min,max) , but how do I use it to select that exact row from the query?

require 'DB.php';
$link = mysql_connect('localhost', 'root', '430123');
$db = mysql_select_db('bakery', $link);
$result = mysql_query('SELECT * FROM quotes');

I could use a for loop and use mysql_fetch_row() for how much the number from rand() was, but that could be a bit inefficient maybe?

To get only the 4th row use limit offset, number_of_records

SELECT * FROM quotes
order by rand()
limit 3, 1

好吧,您可以选择所有引号,然后使用array_rand()函数选择随机引号

You can use ORDER BY rand().

eg.

$result = mysql_query('SELECT * FROM quotes ORDER BY rand() limit 3');

Here's a function that returns an array of $count elements given a source array. You have to add support for avoiding duplicate quotes, but this does what you asked.

<?php
    require 'DB.php';    
    $link = mysql_connect('localhost', 'root', '430123');
    $db = mysql_select_db('bakery', $link);
    $result = mysql_query('SELECT * FROM quotes');
    $row = mysql_fetch_array($result);
    get_quotes($row,3);

   function get_quotes($source,$count) {
        $quotes = array();
        for ($i = 0;$i<$count;$i++) {
            $seed = rand(0,sizeof($source)-1);
            $quotes[] = $source[$seed];
        }
        return $quotes;        
    }

Maybe doing it in a query would be better, but I don't think that's what you asked for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM