Perl – How to connect to mysql database and fetch data!


Learn how to connect to DB and show results on the browser using Perl, Here you are actually going to learn Web Development using Perl programming. I hope you are a beginner and want to learn a new stuff in Perl programming. I’m going to teach you how to connect to the MySQL database in Perl and fetch records from a table. Its very simple.

NOTE: You can demo & download the script at the bottom of the page!.

To create a connection in Perl, you need to use the DBI database interface module and connect() function, Write the following to connect to the database:

use DBI;
$dbconnect = DBI->connect('dbi:mysql:databasename:hostname','username','password') or die "Connection Error: $DBI::errstrn";

Entire code is here, Connecting to the database and fetching results,
See the below code and you can understand it easily by reading the comments in that!.

##these two lines are used to display errors on browser. If you don't want, you can remove these
use CGI;
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
##error display ends

##below line is important if you want to display the result in browser
print "Content-type: text/htmlnn";

##use Perl Database Interface
use DBI;
$dbconnect = DBI->connect('dbi:mysql:mydatabase:localhost','myusername','mypassword') or die "Connection Error: $DBI::errstrn";

$sql = "select * from mytable";
##prepare sql query and execute it
$query = $dbconnect->prepare($sql);
$query->execute or die "SQL Error: $DBI::errstrn";

#now go throgh all the records one by one using while loop and print the result
print "<table border='1'>";
while ($result = $query->fetchrow_hashref()){
print "<tr><td>$result->{columname1}</td><td>$result->{columname2}</td></tr>";
print "</table>";

See the demo or download the code!


Add a Comment

Your email address will not be published. Required fields are marked *