我试图从我的表中选择行引用和作者并回显它
我的目标是创建一个随机引用生成器并显示实际引用和作者。
我在表格中输入了25个引号,包含3行(ID,引用,作者)
我的代码如下,我不断收到资源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";
?>
请帮助
答案 0 :(得分:6)
首先,我认为你想要
<?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";
?>
但我还有其他建议
预加载所有报价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;
现在根据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);
这应该可以扩展,因为@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";
?>
试一试!!!
答案 1 :(得分:1)
你不能将$ result作为字符串
回显DO
WHILE ($row = mysql_fetch_array($result)):
echo $row['author'] . " " . $row['quote'];
ENDWHILE;
?>
答案 2 :(得分:1)
你没有回应正确的变量。
echo $row['author'] . ": " . $row['quote'];
答案 3 :(得分:1)
为什么AND
只是逗号。
SELECT author, quote FROM inspirational_quotes ORDER BY RAND() LIMIT 1
<强> MySQL Select syntax 强>
答案 4 :(得分:1)
我建议您通过PHP随机化结果以提高性能。例如:
$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");