是的我是学生,是的,这是一项任务,但我只是需要一些帮助清理。我不打算让别人为我做作业。
所以我有一个包含5本书的数据库,其中包含6个不同的数据列。我正在尝试创建一个可以搜索该数据库并在表中返回结果的perl程序。我必须添加一种方法将它们添加到购物车中,但稍后会出现。
Perl的问题是我不知道如何检查为什么我收到“内部服务器错误”。应用程序进入Perl页面,所以我猜它不是那个。
#!/usr/bin/perl
use warnings; # allow for warnings to be sent if error's occur
use CGI qw( :standard ); # not a 100% sure what the rest of these mean but they are like #includs in C++, libraries for reference in the code
use DBI;
use DBD::mysql; #database data will come from mysql
my $dbh = DBI->connect( "DBI:mysql:DATABASE NAME", "USERNAME", "PASS REMOVED" ) or
die( "Could not make connection to database: $DBI::errstr" ); # connect to the database with address and pass or return error
$term = $SEARCHTERM[]; #set the search char to $term
$term =~ tr/A-Z/a-z/; #set all characters to lowercase for convenience of search
$sql = "SELECT * FROM Books WHERE Title LIKE %$term% OR Description LIKE %$term% OR Author LIKE %$term%" or die ("$term may have not worked"); #set the query string to search the database
$sth = $dbh->prepare($sql); # prepare to connect to the database
$sth->execute # connect to the database
or die "SQL Error: $DBI::errstr\n"; #or return an error
while (@data = $sth->fetchrow_array) { #while we are grabbing he queried data do a table setup and set variables for table
print "<table width=\"100%\" border=\"0\"> ";
$title = $data[0];
$desc = $data[1];
$author = $data[2];
$pub = $data[3];
$isbn = $data[4];
$photo = $data[5];
print "<tr> <td width=50%>Title: $title</td> <td width=50% rowspan=5>$photo</td></tr><tr><td>Discreption Tags: $desc</td></tr><tr><td></td></tr><tr><td>Author: $author</td></tr><tr><td>ISBN: $isbn</td>
</tr></table> \n";
}
请帮忙!
答案 0 :(得分:4)
早些时候,有人建议,
my $sql = "
SELECT *
FROM Books
WHERE Title LIKE '%$term%'
OR Description LIKE '%$term%'
OR Author LIKE '%$term%'
";
my $sth = $dbh->prepare($sql);
$sth->execute();
假设他对你的问题是正确的,这是不正确的。考虑如果有人搜索标题会发生什么事情&#34; Foo&#39;&#34; ...
选项1:
my $sql = '
SELECT *
FROM Books
WHERE Title LIKE '.$dbh->quote("%$term%").'
OR Description LIKE '.$dbh->quote("%$term%").'
OR Author LIKE '.$dbh->quote("%$term%").'
';
my $sth = $dbh->prepare($sql);
$sth->execute();
选项2:
my $sql = '
SELECT *
FROM Books
WHERE Title LIKE ?
OR Description LIKE ?
OR Author LIKE ?
';
my $sth = $dbh->prepare($sql);
$sth->execute("%$term%", "%$term%", "%$term%");
答案 1 :(得分:2)
首先,我还强烈建议您将use strict;
添加到脚本的顶部,然后修复您将获得的错误,主要是使用my
声明您的变量。
我也可以建议使用现代框架,比如说Mojolicious而不是使用过时的CGI模块。它们都可以在类似CGI的环境下运行,并且更容易使用!
最后,您应该避免将变量插入到SQL字符串中,因为它存在巨大的安全风险!有关此主题的更多信息,请访问此网站:http://bobby-tables.com/
答案 2 :(得分:1)
您的选择无效。变化
$sql = "SELECT * FROM Books WHERE Title LIKE %$term% OR Description LIKE %$term% OR Author LIKE %$term%"
到
$sql = "SELECT * FROM Books WHERE Title LIKE '%$term%' OR Description LIKE '%$term%' OR Author LIKE '%$term%"'
应引用LIKE
的模式文字。