10.07.2015 Views

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 3 ■ DATABASES AND PERL 61my $dbh = DBI->connect($dsn,$username,$password)or die "Cannot connect <strong>to</strong> database: $DBI::errstr";my $sth = $dbh->prepare("SELECT user,host FROM mysql.user");$sth->execute() or die "Cannot execute sth: $DBI::errstr";print $sth->dump_results();$dbh->disconnect();The output is as follows:'postfix', 'localhost''root', 'localhost''', 'netserver''testuser', 'localhost''user', 'localhost'3 rowsFinish()-ing the StatementIt is a good idea <strong>to</strong> be aware of the result set that you’re working with from a given statementhandle. If you don’t retrieve all of the rows from a query, the result set will still hold data. Thiscan mean extra memory usage for the database server and can also result in warnings whenyou attempt <strong>to</strong> execute the disconnect() method. Therefore, if you won’t be retrieving all ofyour results, be sure <strong>to</strong> use the finish() method on the statement handle <strong>to</strong> flush the results.In the examples shown, all of the results were retrieved by iterating through them usingfetchrow_array() or dump_results(). However, if this hadn’t been the case, I would have usedthe finish() method, like this:$sth->finish();Using the Quote Method for Dynamic StatementsIn the examples shown so far, there’s no reason why you couldn’t substitute a valid variablewithin the SQL statement. In other words, instead of merely using this:SELECT host FROM mysql.user;you could, assuming a variable of $username, use this:SELECT host FROM mysql.user WHERE user = '$username';In this example, the variable $username is interpolated, and whatever is in $username will besent with the query. This interpolation of $username is as opposed <strong>to</strong> parameterizing or bindingfor dynamic statements, as you’ll see in the “Binding Parameters” section, coming up soon.A popular vec<strong>to</strong>r for attackers exploiting database connectivity (particularly in web applications)is <strong>to</strong> include characters or other anomalies in an attempt <strong>to</strong> get the program, and thereforethe database server, <strong>to</strong> execute additional commands. These types of attacks are made possible

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!