Reputation: 33
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
Upvotes: 3
Views: 7271
Reputation: 44373
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 !!!
Upvotes: 7
Reputation: 171
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");
Upvotes: 1
Reputation: 33391
Why AND
just comma.
SELECT author, quote FROM inspirational_quotes ORDER BY RAND() LIMIT 1
Upvotes: 1
Reputation: 14691
You are not echoing the right variable.
echo $row['author'] . ": " . $row['quote'];
Upvotes: 1
Reputation: 5084
You cant echo $result as a string
do
WHILE ($row = mysql_fetch_array($result)):
echo $row['author'] . " " . $row['quote'];
ENDWHILE;
?>
Upvotes: 1