database - Select one random row from cycle of function with SQLite and Perl -
hi tried select 1 random number this:
my source:
use dbi; use cgi; $file = '.\input.txt'; # name file open(file, $file) or die("unable open file"); @data = <file>; foreach $line (@data) { chomp $line $sth = $dbh->prepare("select columna table columna '%$line%'"); $sth->execute; $result = $sth->fetchall_arrayref; foreach $row ( @$result ) { print "- "; print "@$row\n"; print "<br />"; } }
how can print 1 random row??? tried that:
my $sth = $dbh->prepare("select nazov_receptu recepty nazov_receptu '%$line%' , kategoria == 'p' , (rowid = (abs(random()) % (select max(rowid)+1 recepty)) or rowid = (select max(rowid) recepty)) order rowid limit 1;");
but not clear... dont know why...
i using sqlite , printing web interface.
you can try when have input.txt:
a c
database:
id name 1 2 b 3 c 4 d 5 e
out:
a or c (random)
why not join file arguments query right away instead of looping on them? simple matter extract random index in perl:
use strict; use warnings; # use these 2 pragmas $file = '.\input.txt'; open $fh, "<", $file or die "unable open file: $!"; chomp(my @data = <$fh>); # chomp lines @ once $query = "select columna table "; $query .= join " or ", ( "columna ?" ) x @data; # add placeholder each line @data = map "%$_%", @data; # add wildcards $sth = $dbh->prepare($query); $sth->execute(@data); # execute query lines argument $result = $sth->fetchall_arrayref; $randid = rand @$result; # find random index $row = $result->[ $randid ]; print "- @$row\n"; print "<br />";
as see, i've used placeholders, proper way use variables queries. happens simple way handle arbitrary amount of arguments. because include lines in query, not need for
loop.
as see, i've changed few other small details, such using 3 argument open
lexical file handle, including error variable $!
in die
statement, using proper indentation, using strict
, warnings
(you should never code without them)
i've handled randomization in perl because simplest me. may simple , more effective handle in sql query. may tack on order random() limit 1
end of it, , might work fine too.
Comments
Post a Comment