CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Advanced:
Perl/DBI:mysql Question

 



Dubbs1231
newbie

Nov 22, 2000, 9:29 AM

Post #1 of 6 (1333 views)
Perl/DBI:mysql Question Can't Post

Using DBI:mysql in a CGI script, how would I select a random row from a specified table?

Thanks!!!

Erich Musick aka Dubbs


perlplexer
Deleted

Nov 22, 2000, 11:03 AM

Post #2 of 6 (1333 views)
Re: Perl/DBI:mysql Question [In reply to] Can't Post

 
$sth = $dbh->prepare( qq{
SELECT foo, bar FROM table;} );
$sth->execute;

while((@row=$sth->fetchrow_array)?@rl=@row:0){
last
if rand(length $row[rand($#row)]) <
0.5*(length $row[rand($#row)]);
}
print "Random line: @rl\n"

@rl is your random line...
You can play with the condition a bit more
though...

or just do

SELECT count(*) from table;

and then use the value returned by that
SQL statement in rand();

or use fetchall_arrayref() to fetch all rows, determine size of the resulting array and get a random line from it...

perldoc DBI is your friend. :)


Dubbs1231
newbie

Nov 22, 2000, 12:14 PM

Post #3 of 6 (1333 views)
Re: Perl/DBI:mysql Question [In reply to] Can't Post

Thanks!!!! One other thing, if I wanted to do something like SELECT count(*) from table; and put that value into a scalar, let's say $count, how would I do it using DBI?

Thanks a ton!!!!!

Erich Musick


perlplexer
Deleted

Nov 22, 2000, 12:26 PM

Post #4 of 6 (1333 views)
Re: Perl/DBI:mysql Question [In reply to] Can't Post

i have not tested it but you should be able
to say:

$sth = $dbh->prepare(qq{SELECT count(*) FROM table;});
$sth->execute;
@row = $sth->fetchrow_array;

$row[0] should have the number of rows...


Dubbs1231
newbie

Nov 22, 2000, 1:01 PM

Post #5 of 6 (1333 views)
Re: Perl/DBI:mysql Question [In reply to] Can't Post

Awesome!!! It works!!! Thank you so much! :)

Erich Musick


jack.chicrac
Deleted

Dec 5, 2000, 5:36 AM

Post #6 of 6 (1333 views)
Re: Perl/DBI:mysql Question [In reply to] Can't Post

my $sth=$dbh->prepare("$reqsql");
$sth->execute();
$num_rows=$sth->rows();
if ($num_rows==0)
{
&erreur;
}
else {
etc......
}

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives