2

我试图从我的表中选择行引用和作者并回显它

我的目标是创建一个随机报价生成器并显示实际报价和作者。

我在表中输入了 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";
?>

请帮忙

4

5 回答 5

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 的返回值来自 id 列表,quoteID 表中没有间隙。

<?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";
?>

试试看 !!!

于 2013-01-30T21:50:38.697 回答
1

您不能将 $result 回显为字符串

    WHILE ($row = mysql_fetch_array($result)):
     echo $row['author'] . " " . $row['quote'];
ENDWHILE; 


?>
于 2013-01-30T21:50:26.747 回答
1

您没有呼应正确的变量。

echo $row['author'] . ": " . $row['quote'];
于 2013-01-30T21:50:28.733 回答
1

为什么AND只是逗号。

SELECT author, quote FROM inspirational_quotes ORDER BY RAND() LIMIT 1

MySQL 选择语法

于 2013-01-30T21:50:49.433 回答
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");
于 2013-01-30T21:53:53.297 回答