简体   繁体   中英

Perl - passing user inputted cgi form data to perl program to be then put into mysql database

I've tried searching forums for a solution, however most of the answers were either too difficult to understand. SO I'm in the process of making a website for a small community, and currently we have our database and html design layout, but I'm getting snagged on how to push my Perl CGI form into another Perl program to then alter my database.

Here is the Perl controller that alters the database tables (and it works):

#!/usr/bin/perl -w
#!/usr/bin/perl -wT

# DBI is the standard database interface for Perl
# DBD is the Perl module that we use to connect to the <a href=http://mysql.com/>MySQL</a> database
use DBI;
use DBD::mysql;

use warnings;

#----------------------------------------------------------------------
# open the accessDB file to retrieve the database name, host name, user name and password
open(ACCESS_INFO, "accessDB.txt") || die "Can't access login credentials";


# assign the values in the accessDB file to the variables
my $database = <ACCESS_INFO>;
my $host = <ACCESS_INFO>;
my $userid = <ACCESS_INFO>;
my $passwd = <ACCESS_INFO>;
my $tablename = "Article";

# the chomp() function will remove any newline character from the end of a string
chomp ($database, $host, $userid, $passwd);

# close the accessDB file
close(ACCESS_INFO);
#----------------------------------------------------------------------

# invoke the ConnectToMySQL sub-routine to make the database connection
$connection = ConnectToMySql($database);

if ($tablename == "Article"){
    $connection = InsertArticle($database);
}

elsif ($tablename == "Category"){
    $connection = InsertCategory($database);

}
elsif ($tablename == "Comment"){
    $connection = InsertComment($database);

}
elsif ($tablename == "User"){
    $connection = InsertUser($database);

}
else {
    print "No such table found. Contact website administrator.\n"

}
sub InsertArticle{

$query = "insert into $tablename (Id, CategoryId, UserId, Title, Content) values(?, ?, ?, ?, ?)";

$statement = $connection->prepare($query);


$statement->execute('undef', '1', '1029', 'Dota2>League', 'textfromarticle');
}
sub InsertCategory{

$query = "insert into $tablename (Id, CategoryId, UserId, Title, Content) values(?, ?, ?, ?, ?)";

$statement = $connection->prepare($query);


$statement->execute('undef', '1', '1029', 'Dota2>League', 'textfromarticle');
}
sub InsertComment{

$query = "insert into $tablename (Id, CategoryId, UserId, Title, Content) values(?, ?, ?, ?, ?)";

$statement = $connection->prepare($query);


$statement->execute('undef', '1', '1029', 'Dota2>League', 'textfromarticle');
}
sub InsertUser{

$query = "insert into $tablename (Id, CategoryId, UserId, Title, Content) values(?, ?, ?, ?, ?)";

$statement = $connection->prepare($query);


$statement->execute('undef', '1', '1029', 'Dota2>League', 'textfromarticle');
}

exit;

#--- start sub-routine ------------------------------------------------
sub ConnectToMySql {
#----------------------------------------------------------------------

my ($db) = @_;

# assign the values to your connection variable
my $connectionInfo="dbi:mysql:$db;$host";

# make connection to database
my $l_connection = DBI->connect($connectionInfo,$userid,$passwd);

# the value of this connection is returned by the sub-routine
return $l_connection;

}

#--- end sub-routine --------------------------------------------------

In the future, I'll define the other tables in my database through global variables that depend on what button the user presses on the correct webpage. As in, if they're viewing a list of articles, an option at the top would be "submit an article". And from there, the form CGI would be sent to them that they can fill out.

And here is the CGI that makes the form that would be submitted to the above controller script to alter the table:

#!/usr/bin/perl
#!/usr/bin/perl -wT
    use strict;
    use warnings;
    use CGI;
    use CGI::Carp qw(fatalsToBrowser); #remove this in production

 my $q = new CGI;
 print $q->header;                                                  #Content-Type: text/html; charset=ISO-8859-1
 print $q->start_html(
    -title => 'submit an Article',                                  #page name
    -style => {'src' => '/dmrwebsite/dmrwebsite/userinterface'},    #link to style sheet
    );
print $q->start_form(
    -name => 'submitting an Article',
    -method => 'POST',
    enctype => &CGI::URL_ENCODED,
    -onsubmit => 'return true',
    -action => '/dmrwebsite/dmrwebsite/controller.addtotable.pl',
);
print $q-.textfield(
    -name => 'title',
    -value => 'default value',
    -required,
    -size => 20,
    -maxlength =>50,
);
print $q->textarea(
    -name => 'content',
    -value => 'default value',
    -required,
    -maxlength => 1000,
    -cols => 60,
);
print $q->textarea(
    -name => 'url',
    -value => 'default value',
    maxlength => 100,
    cols =>60,
);
print $q-checkbox(
    -name => 'humancheck',
    -checked => 1,
    -value => 'two',
    -label => 'The number two',
);
print $q-submit(
    -name => 'submit_Article',
    -value => 'submit Article',
    -onsumbit => 'javascript: validate_form()',
);
if ($q->param()) {
    submit_form($q);
} else {
    print "Please check your form for inaccuracies.";
}
sub submit_form($){
    my ($q) = @_;


}
print $q->end_form; #ends the form html
print $q->end_html; #end the html document

So basically what I'm stuck at is understand how to send the form data to the perl script in which I can then define the table data in my $tablename = "Article"; and $statement->execute('undef', '1', '1029', 'Dota2>League', 'textfromarticle'); .

Also, I don't have a javascript program to send to the parameter -onsubmit => javaapplication(), . Is that needed? Can I substitute my own Perl program to check the user inputted fields? And how would I call this function? IN the same file or can it just be in the parent directory like /website/perlchecker.pl?

Any help would be greatly appreciated as I'm only a couple days into using Perl let alone CGI and html. Got a couple people helping me on the front end of the website though.

Thanks, -Ori

So many suggestions...

Firstly, your DB insertion program seems to just insert fixed data, so I'm not sure how you think that it works. Also, the if ($tablename == "Article") (and similar) line doesn't do what you want it to. You need to use eq instead of == .

To answer the question that you asked - you need to change your database program so that it accepts input (probably command line arguments) containing the data that you want inserted into the database. You would then add to your CGI program a line that calls this program (probably using system() ) passing it the data from the CGI parameters on the command line.

The code would look something like this:

my $title   = $q->param('title');
my $content = $q->param('title');
# ... other params ...
system('db_script.pl', 'Article', $title, $content, ...)';

But please don't do that. That's a terrible idea.

Instead, I highly recommend that you re-write your database manipulation program as a module. That way, you can load the module into any program that needs to talk to the database and access the database by calling functions rather than by calling an external program. If it was down to me, then I'd definitely use DBIx::Class to produce this library - but I realise that might well be seen as rather advanced.

Then there's the elephant in the room. You're still using CGI to write your web interface. The CGI module has been removed from the latest version of Perl as it is no longer considered best practice for writing web applications. I recommend looking at CGI::Alternatives to find out about other, more modern, tools.

But if you're determined to carry on writing your program as a CGI program, then at the very least, please don't use the HTML generation functions. We've known that including your HTML in your program source code is a terrible idea for at least fifteen years. There's no reason to still be doing it in 2015. You should really be using some kind of templating engine to separate your HTML from your Perl code. I recommend the Template Toolkit .

I'm not sure where you are learning these techniques from, but your source seems to be a good ten years behind accepted best practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM