Beefy Boxes and Bandwidth Generously Provided by pair Networks DiBona
Keep It Simple, Stupid
 
PerlMonks  

Re: Display row number perl DBI

by moritz (Cardinal)
on May 28, 2012 at 16:32 UTC ( #972842=note: print w/ replies, xml ) Need Help??


in reply to Display row number perl DBI

Always use strict; use warnings; at the beginning of your perl code. It catches common mistakes, including the one you are making.

The problem is that Perl replaces variable names in double-quoted strings by their value (we call that "interpolation"), and @rownum happens to look like a variable name in Perl. So use single-quote strings instead:

$sth = $dbh->prepare('Select @rownum:=@rownum+1 rank, p.* from player +p, (SELECT @rownum:=0) r order by score desc limit 10');


Comment on Re: Display row number perl DBI
Select or Download Code
Re^2: Display row number perl DBI
by romy_mathew (Beadle) on May 28, 2012 at 17:50 UTC
    Hi Thanks that worked ...but what if I need to use a variable in limit e.g

    my $temp = 50;

    $sth = $dbh->prepare('Select @rownum:=@rownum+1 rank, p.* from player +p, (SELECT @rownum:=0) r order by score desc limit $temp');

      You use placeholders:

      $sth = $dbh->prepare('Select @rownum:=@rownum+1 rank, p.* from player ++p, (SELECT @rownum:=0) r order by score desc limit ?'); # and later $sth->execute($temp);

      This is generally safer than interpolating variables into SQL strings, and prevents SQL injection attacks.

      See also: DBI, and perlop for the rules about string interpolation and escaping.

      you can also use backslash
      $sth = $dbh->prepare("Select \@rownum:=\@rownum+1 rank, p.* from playe +r +p, (SELECT \@rownum:=0) r order by score desc limit $temp");
      but it looks a little oddly

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://972842]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (10)
As of 2013-05-23 21:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best material for plates (tableware) is:









    Results (492 votes), past polls