2013-02-25 152 views
2

我想創建一個基於perl的cgi來顯示我的相冊,現在我正在對照片進行排序功能。我在mysql中存儲了每張照片的信息。要顯示所有照片,我必須先獲取信息。無法從Perl數據庫中獲取排序數據

問題出在這裏:我期待從mysql獲取的數據按每張照片的文件大小排序,但fetchrow_array()的結果是根據插入到mysql中的時間進行數據排序。

在mysql外殼,我測試

SELECT * FROM album ORDER BY filesize; 

這給由文件大小排序的預期結果。這裏是我的源代碼的一部分:

#!/usr/bin/perl -w 
use strict; 
use CGI; 

my $sort = 'filesize'; 

# Connect the database 
my $dbh = do 'db.pl'; 

# Prepare to print out the pictures 
my $query; 
$query = $dbh->prepare("SELECT * FROM album ORDER BY ?") or die $DBI::errstr; 
$query->execute($sort) or die $DBI::errstr; 

# Print out all pictures 
while(my @data = $query->fetchrow_array()){ 
    # Process fetched data 
    (my $id, my $user, my $filepath, my $filename, my $filesize, my $uploadtime, my $description, my $tfilepath, my $sessioninfo) = @data; 
    print '<fieldset>'; 

    # Display thumbnail 
    print '<a href="', $filepath, '"><img src="', $tfilepath, '" title="', $description, '"></a>'; 

    # Display filename 
    print '</br>'; 

    print $filename; 
    print '</fieldset>';  
} 

# Finish printing out all fetched pictures 
$query->finish; 

我使用錯誤的命令?或者我正在使用錯誤的方法來執行排序功能? 感謝您的幫助!

+2

IFAIK佔位符只能爲值一起使用。 – Toto 2013-02-25 10:07:07

回答

3

ORDER BY需要一個字段名稱,而不是一個表達式。

my $query = "SELECT * FROM album ORDER BY ".$dbh->quote_identifier($sort); 
my $sth = $dbh->prepare($query); 
$sth->execute(); 

順便說一句,你有對輸出端的錯誤了。如果$description包含「"」,「&」或「<」,該怎麼辦?你需要一些逃跑。

sub text_to_html { 
    my ($s) = @_; 
    $s =~ s/&/&amp;/g; 
    $s =~ s/</&lt;/g; 
    $s =~ s/>/&gt;/g; 
    $s =~ s/"/&quot;/g; 
    $s =~ s/'/&apos;/g; 
    return $s; 
} 

順便提一下,

(my $id, my $user, my $filepath, my $filename, 
my $filesize, my $uploadtime, my $description, 
my $tfilepath, my $sessioninfo) = @data; 

可以寫成

my ($id, $user, $filepath, $filename, 
    $filesize, $uploadtime, $description, 
    $tfilepath, $sessioninfo) = @data; 
+0

它的工作原理,謝謝!順便說一下,爲了逃避,爲什麼不使用CGI-> escapeHTML($ description)? – SSheldon 2013-02-25 10:20:11