Re: [SQL] placeholders

From: "Gene Selkov Jr(dot)" <selkovjr(at)mcs(dot)anl(dot)gov>
To: martin(at)axe(dot)net(dot)au, pgsql-sql(at)postgresql(dot)org
Subject: Re: [SQL] placeholders
Date: 1999-01-06 16:05:58
Message-ID: 199901061604.KAA02423@antares.mcs.anl.gov
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

> Hi,
>
> I am using
> - Postrges 6.3.2
> - DBI 0.93
> - DBD-pg 0.73
> - Slackware 3.3 Linux
>
> I am accessing the database using a perl
> CGI program.
>
> I need to be able to list records from a
> database in various sort orders. The user
> needs to be able to select the sort order
> using a web form.

[...]

>
> I want to be able to change the code so the
> field name in the order by clause is variable
>
> eg. instead of
> ORDER BY title DESC
>
> I want to say
> ORDER BY :4 DESC
>
> and in the execute statement
> $sth1->execute (("$category\%"),("$keywords\%"), ("$postedby\%"))
>
> add a fourth variable ("$orderby") which
> will be set to title, dateposted or
> userlastupdate
>
> However if I use ("$orderby") as the
> fourth variable and set $orderby to
> title then my trace shows DBI puts
> 'title' into the SQL SELECT statement
> not title and I get an invalid syntax
> error. I need to find a way to stop
> putting the ' ' around title.
>
> Is there any way I can make the order by
> operand a variable ??
>

What's wrong with:

@column = ("catalogid", "productid", ..., "category");

... ORDER BY $column[3] DESC ...

If you want it real smart, you can run a query to obtain column names
from the database.

Also, since you are using perl anyway, you might as well delegate
ordering to perl. If you read your entire query output to an array of
strings where values are delimited with something, e. g., "\t", you
could say:

$colToSortOn = 2;
$descending = 1; # otherwise $descending = undef;
foreach ( sort {
@a = split "\t", $a;
@b = split "\t", $b;
($descending ? $b[$colToSortOn] <=> $a[$colToSortOn] : $a[$colToSortOn] <=> $b[$colToSortOn])
} @result # @result comes from your query
) {
@values = split "\t";
# do your display stuff here
}

See man perlfunc /sort SUBNAME for more details on sort()

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Jackson, DeJuan 1999-01-06 19:32:27 RE: [SQL] Kind of Funny
Previous Message Brook Milligan 1999-01-06 15:12:05 rules and referential integrity