[英]Fetching a random row from MySQL and displaying it with PHP
im trying to select the row quote and author from my table and echo it 我试图从我的表中选择行引用和作者并回应它
my goal is to create a random quote generator and display the actual quote and author. 我的目标是创建一个随机引用生成器并显示实际引用和作者。
I have entered 25 quotes in my table with 3 rows (ID, quote, author) 我在表格中输入了25个引号,包含3行(ID,引用,作者)
my code is the following and i keep getting the resource id #9 error 我的代码如下,我不断收到资源ID#9错误
<?php
mysql_select_db(name of database);
$quotes = "SELECT author AND quote FROM inspirational_quotes ORDER BY RAND() LIMIT 1";
$result = mysql_query($quotes);
WHILE ($row = mysql_fetch_array($result)):
ENDWHILE;
echo "$result";
?>
please help 请帮忙
First of all, I think you want 首先,我想你想要
<?php
mysql_select_db(name of database);
$quotes = "SELECT author,quote FROM inspirational_quotes ORDER BY RAND() LIMIT 1";
$result = mysql_query($quotes);
WHILE ($row = mysql_fetch_array($result)):
ENDWHILE;
echo "$result";
?>
but I have an additional suggestion 但我还有一个建议
Preload all the quote IDs 预加载所有报价ID
CREATE TABLE quoteID
(
ndx int not null auto_increment,
id int not null,
PRIMARY KEY (ndx)
);
INSERT INTO quoteID (id) SELECT id FROM inspirational_quotes;
Now choose based on the id from quoteID table 现在根据quoteID表中的id选择
SELECT B.author,B.quote FROM quoteID A INNER JOIN inspirational_quotes B
USING (id) WHERE A.ndx = (SELECT CEILING(MAX(ndx) * RAND()) FROM quoteID);
This should scale just fine because the return value for @rnd_id comes from a list of ids with no gaps in the quoteID table. 这应该可以正常扩展,因为@rnd_id的返回值来自一个在quoteID表中没有间隙的id列表。
<?php
mysql_select_db(name of database);
$quotes = "SELECT B.author,B.quote FROM quoteID A INNER JOIN "
. "inspirational_quotes B USING (id) "
. "WHERE A.ndx = (SELECT CEILING(MAX(ndx) * RAND()) FROM quoteID)";
$result = mysql_query($quotes);
$row = mysql_fetch_array($result);
echo "$result";
?>
Give it a Try !!! 试试看 !!!
You cant echo $result as a string 你不能将$ result作为字符串回显
do 做
WHILE ($row = mysql_fetch_array($result)):
echo $row['author'] . " " . $row['quote'];
ENDWHILE;
?>
你没有回应正确的变量。
echo $row['author'] . ": " . $row['quote'];
Why AND
just comma. 为什么AND
刚刚逗号。
SELECT author, quote FROM inspirational_quotes ORDER BY RAND() LIMIT 1
I suggest you to randomize results by PHP to improve performance. 我建议你通过PHP随机化结果来提高性能。 eg.: 例如。:
$r = mysql_query("SELECT count(*) FROM inspirational_quotes");
$d = mysql_fetch_row($r);
$rand = mt_rand(0,$d[0] - 1);
$r = mysql_query("SELECT author,quote FROM inspirational_quotes LIMIT $rand, 1");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.