2

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)

my code is the following and i keep getting the resource id #9 error

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

4

5 に答える 5

6

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

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

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.

<?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 !!!

于 2013-01-30T21:50:38.697 に答える
1

You cant echo $result as a string

do

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


?>
于 2013-01-30T21:50:26.747 に答える
1

You are not echoing the right variable.

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

Why AND just comma.

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

MySQL Select syntax

于 2013-01-30T21:50:49.433 に答える
1

I suggest you to randomize results by PHP to improve performance. 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");
于 2013-01-30T21:53:53.297 に答える