Connecting to a MySQL Database Using CGI/Perl

This example describes using CGI/Perl to connect to a MySQL Database.

#!/usr/bin/perl use cPanelUserConfig;
print "ContentType: text/html\n\n";

use DBI;

# Connecting to the database
# Replace DATABASENAME with the name of the database,
# HOSTNAME with the hostname/ip address of the MySQL server.
$drh = DBI->install_driver("mysql");
$dsn = "DBI:mysql:database=your_databasename;";
$dbh = DBI->connect($dsn,\'your_dbusername\',\'your_dbpassword\');

# Select the data and display to the browser

my $sth = $dbh->prepare("SELECT * FROM customers");
while (my $ref = $sth->fetchrow_hashref()) {
print "Found a row: id = $ref->{'id'}, name = $ref->{'name'}";


# Disconnect from the database.


Was This Article Helpful?
Thanks for your feedback. To speak with a customer service representative, please use the support phone number or chat option above.
Glad we helped! Anything more we can do for you?
Sorry about that. Tell us what was confusing or why the solution didn’t solve your problem.