Perl web service : Using XML RPC
Something is wrong with this code.
#!/use/bin/perl
use strict;
use warnings;
use Frontier::Daemon;
use DBI;
sub credentials {
my ($username, $password) = @_;
my $tablename = "users";
my $user = "db_user";
my $pw = "db_pass";
$dbh = DBI->connect('DBI:mysql:database;host=localhost', $user, $pw, {RaiseError => 1});
$sql = "SELECT username, password FROM $tablename";
$sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
if ($sth->rows > 0) {
$login_response = "Login Successful";
} else {
$login_response = "Invalid Credentials";
return {'login' => $login_response};
die();
}
}
$methods = {'login.credentials' => \&credentials,};
Frontier::Daemon->new(Loc开发者_如何学运维alPort => 8080, methods => $methods)
or die "Couldn't start HTTP server: $!";
This is another problem with your code - you're not doing anything with the supplied username and password. You need to add a where clause to your SQL statement, so:
my $sql = 'SELECT * FROM users WHERE username = ? AND password = ? ';
my $sth = $dbh->prepare($sql);
$sth->execute($username, $password);
However, given that your example is selecting all records from the 'users' table, I'd have thought that credentials() would at least be returning some rows. However, I'm afraid that I've not used Frontier::Daemon in the past, so I'm not able to help on that front.
I also can't see how this code would work given that you are using strictures. $dbh, $sql, $sth and $login_response haven't been declared. So make sure that you're using 'my' in the right places - as per my example above.
To fix the problems you mentioned with returning the correct string - the logic in your if statement isn't quite right. You are returning the string 'Login Successful' when there's a successful login and the hashref { login => $login_response } when no user could be found.
I think the confusion arose from the layout of the braces. I must stress that you try and indent you code properly, which will make it much more readable to yourself and other developers when debugging and maintaining the code in the future.
The following logic should do the job.
if($sth->rows > 0){
return "Login Successful";
}
return "Invalid Credentials";
精彩评论