从MySQL表中检索CGI表单文本框中的值

时间:2013-05-10 23:24:48

标签: forms perl cgi

我在cgi文件中看起来像这样:

print "<FORM NAME='LAYOUTFORM' ACTION='Handler.cgi' METHOD=POST>";
print "<table border='0' align=center>\n";
print "<tr><td>Search by:<SELECT ID='Forms Combo Box1' NAME='what_to_do'><OPTION VALUE='title'>Title</OPTION><OPTION VALUE='description'>Description</OPTION><OPTION   VALUE='author'>Author</OPTION></td>";
print "<td><INPUT ID='SearchArea' TYPE=TEXT NAME='searchbox' VALUE='' SIZE=27 MAXLENGTH=100></td>";
print "<td><INPUT TYPE=SUBMIT NAME='searchbutton' VALUE='Search' ID='Form_Search'></td></tr>";
print "</table>\n";
print "</form>";

然后我有了这个:

#!/usr/local/bin/perl

use DBI;
use DBD::mysql;
use CGI qw(:standard);

$searchinput = param('searchbox');

print "Content-type: text/html\n\n";

my $dbh = DBI->connect( "DBI:mysql:database", "username", "password" ) or
die( "Could not make connection to database: $DBI::errstr" );

my $sth = $dbh->prepare( q(SELECT * FROM BookStore WHERE bAuthor = $searchinput) ) or 
die( "Cannot prepare statement: ", $dbh->errstr(), "\n" );

my $rc = $sth->execute() or
die( "Cannot execute statement: ", $sth->errstr(), "\n" );

我在命令行中收到此错误:

Uknown column '$searchinput' in 'where clause' at Search.cgi line 17.

我要做的是用户将在main.cgi的文本框中输入名称。然后点击搜索按钮,search.cgi将检索表格列中匹配的行的信息。

1 个答案:

答案 0 :(得分:1)

尝试更改此行:

my $sth = $dbh->prepare( q(SELECT * FROM BookStore WHERE bAuthor = $searchinput) ) or 
die( "Cannot prepare statement: ", $dbh->errstr(), "\n" );

要:

my $query = sprintf ('SELECT * FROM BookStore WHERE bAuthor = %s', 
                     $dbh->quote("$searchinput"));