我正在尝试创建一个基于perl的cgi来显示我的相册,现在我正在研究照片的排序功能。我将每张照片的信息存储在mysql中。要显示所有照片,我必须先获取信息。
这就是问题:我期望从mysql获取的数据是按照每张照片的文件大小排序的,但是fetchrow_array()的结果是根据插入到mysql中的时间对数据进行排序。
在mysql shell中,我测试了
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;我是不是用错了命令?或者我使用了一种错误的方法来执行排序功能?感谢您的帮助!
发布于 2013-02-25 18:02:19
ORDER BY接受字段名,而不是表达式。
my $query = "SELECT * FROM album ORDER BY ".$dbh->quote_identifier($sort);
my $sth = $dbh->prepare($query);
$sth->execute();顺便说一句,你在输出端也有bug。如果$description包含""“、"&”或"<“怎么办?你需要一些逃脱。
sub text_to_html {
my ($s) = @_;
$s =~ s/&/&/g;
$s =~ s/</</g;
$s =~ s/>/>/g;
$s =~ s/"/"/g;
$s =~ s/'/'/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;https://stackoverflow.com/questions/15064301
复制相似问题