{"id":110,"date":"2020-02-12T10:36:34","date_gmt":"2020-02-12T10:36:34","guid":{"rendered":"https:\/\/www.lcn.com\/support\/knowledge-base\/how-to-use-a-database-with-perl\/"},"modified":"2020-03-04T17:08:50","modified_gmt":"2020-03-04T17:08:50","slug":"how-to-use-a-database-with-perl","status":"publish","type":"ht_kb","link":"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-perl\/","title":{"rendered":"How to use a database with Perl"},"content":{"rendered":"<p>Connecting to a database is a very common task for cgi scripts but it can be a very involved process. Below we&#8217;ll step through connecting to, inserting into and querying a database and displaying back the results.<\/p>\n<h3>Connecting to the database<\/h3>\n<p>If you haven&#8217;t already created a MySQL database you can follow the <a href=\"\/support\/articles\/how-to-create-a-mysql-database\" target=\"blank\" rel=\"noopener noreferrer\">How to create a MYSQL database<\/a> guide. For the purpose of this example we&#8217;ll use the database name <strong>my_database<\/strong>, remember to replace this with your actual database name.<\/p>\n<p>To make connecting to and using the database easier we&#8217;re going to use the Perl DBI module. Lets start at the top of our script with the location of the Perl interpretor and then we tell Perl we want to use the DBI module and then create a DBI object.<\/p>\n<pre class=\"prettyprint linenums\">#!\/usr\/bin\/perl\n\nuse DBI;\nmy $database_name = \"my_database\";\nmy $database_host = \"mysql.lcn.com\";\nmy $database_user = \"username\";\nmy $database_password = \"password\";\n\nmy $dbh = DBI-&gt;connect(\"dbi:mysql:$database_name:$database_host\", $database_user, $database_password) or die \"Unable to connect: $DBI::errstrn\";<\/pre>\n<p><\/br>The DBI module is object-orientated, this means all of the DBI functions and data are accessed through an instance of DBI, in our script this instance is called <i>$dbh<\/i>, short for database handle.<\/p>\n<p><strong>Lines 4 to 7<\/strong> &#8211; Defines local variable to store our connection data, make sure to update them with your actual database details.<\/p>\n<p><strong>Line 9<\/strong> &#8211; Creates the DBI object by calling the connect function using the variables we defined, if the connection fails the script will die.<\/p>\n<h3>Create a table<\/h3>\n<p>Lets create a simple contacts table and put some details in it. We&#8217;ll store first name, surname and email address.<\/p>\n<pre class=\"prettyprint linenums:10\">my $sql = \"CREATE TABLE IF NOT EXISTS contacts (\nid INT NOT NULL AUTO_INCREMENT,PRIMARY KEY(id),\nfirst_name VARCHAR(64),\nsurname VARCHAR(64),\nemail VARCHAR(255))\";\nmy $sth = $dbh-&gt;prepare($sql);\n$sth-&gt;execute() or die \"SQL Error: $DBI::errstrn\";<\/pre>\n<p><\/br><strong>Lines 10 to 15<\/strong> &#8211; We build a string of SQL to create our table. On line 18 we prepare our SQL statement and assign it to a new local varible <i>$sth<\/i>, short for statement handle.<\/p>\n<p><strong>Line 18<\/strong> &#8211; We call the execute function on our $sth object and pass it our SQL string to actually create the table on the database.<\/p>\n<h3>Insert data into the database<\/h3>\n<p>Next we&#8217;ll put some data into our new table.<\/p>\n<pre class=\"prettyprint linenums:20\">$sth = $dbh-&gt;prepare(\"INSERT INTO contacts(first_name, surname, email) VALUES(?,?,?)\");\n$sth-&gt;execute(\"Nick\", \"Jones\", \"nick.jones@foo.com\");\n$sth-&gt;execute(\"Matt\", \"Smith\", \"matt.smith@bar.com\");\n$sth-&gt;execute(\"Matt\", \"Brown\", \"matt.brown@baz.com\");<\/pre>\n<p><\/br><strong>Line 20<\/strong> &#8211; Here we prepare our new SQL statement, notice at the end of the statement we have a set of question marks. These are used as place-holders for the actual values we will put in when we execute the statement.<\/p>\n<p><strong>Lines 21 to 23<\/strong> &#8211; Executes our SQL statement passing in three values for first name, surname and email to replace the place-holders.<\/p>\n<h3>Query the database<\/h3>\n<p>Now that we&#8217;ve added some data into our database lets query it for all contacts whose first name is Matt.<\/p>\n<pre class=\"prettyprint linenums:24\">$sth = $dbh-&gt;prepare(\"SELECT first_name, surname, email FROM contacts WHERE first_name = ?\");$sth-&gt;execute(\"Matt\");<\/pre>\n<p><\/br>Again, we prepare our SQL statement and use a place-holder for the value of our WHERE clause which tells the database to return all contact where the first_name field equals the value we pass in when we execute our query.<\/p>\n<h3>Display back database results<\/h3>\n<p>Finally, we want to display this data back in a web page.<\/p>\n<pre class=\"prettyprint linenums\">print \"Content-type: text\/plain\\n\\n\";\n\nprint &amp;rlaquo;&lt;HTML_PAGE;\n&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;Database Test&lt;\/title&gt;\n&lt;\/head&gt;\n&lt;body&gt;\n&lt;h1&gt;Database Test&lt;\/h1&gt;\n&lt;table&gt;\n&lt;tr&gt;\n&lt;th&gt;First Name&lt;\/th&gt;\n&lt;th&gt;Surname&lt;\/th&gt;\n&lt;th&gt;Email&lt;\/th&gt;\n&lt;\/tr&gt;\nHTML_PAGE\n\nwhile( $row = $sth-&gt;fetchrow_hashref ) {\nprint \"&lt;tr&gt;&lt;td&gt;$row-&gt;{first_name}&lt;\/td&gt;\";  \nprint \"&lt;td&gt;$row-&gt;{surname}&lt;\/td&gt;\";  \nprint \"&lt;td&gt;$row-&gt;{email}&lt;\/td&gt;&lt;\/tr&gt;\";\n}\n\nprint &lt;&lt;HTML_PAGE;\n&lt;\/table&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;\nHTML_PAGE<\/pre>\n<p><\/br>First print back the HTTP header to let the web browser know what type of content to expect. Then we print out the first part of the HTML page. We use a while loop to iterate over all the results returned by calling the <i>fetchrow_hashref<\/i> function on our <i>$sth<\/i> object, for each result we print out the field data and HTML for a table cell.<\/p>\n<h3>The final script<\/h3>\n<p>This example script shows a very basic way to get form contents emailed to you, it doesn&#8217;t however have the refinements of a professional script, e.g. input validation. Below is the finished script. We&#8217;ve added some comments (lines beginning with #) to help make it clearer.<\/p>\n<pre class=\"prettyprint linenums\">#!\/usr\/bin\/perl\n\nuse DBI;\n\n# Define database details\nmy $database_name = \"my_database\";\nmy $database_host = \"mysql.lcn.com\";\nmy $database_user = \"username\";\nmy $database_password = \"password\";\n\n# Connect to database and create DBI object\nmy $dbh = DBI-&gt;connect(\"dbi:mysql:$database_name:$database_host\", $database_user, $database_password) or die \"Unable to connect: $DBI::errstrn\";\n\n# Create contacts table\nmy $sql = \"CREATE TABLE IF NOT EXISTS contacts (  \nid INT NOT NULL AUTO_INCREMENT,  \nPRIMARY KEY(id),  \nfirst_name VARCHAR(64),  \nsurname VARCHAR(64),  \nemail VARCHAR(255))\";\n\nmy $sth = $dbh-&gt;prepare($sql);\n$sth-&gt;execute() or die \"SQL Error: $DBI::errstrn\";\n\n# Insert data into the table\n$sth = $dbh-&gt;prepare(\"INSERT INTO contacts(first_name, surname, email) VALUES(?,?,?)\");\n$sth-&gt;execute(\"Nick\", \"Jones\", \"nick.jones@foo.com\");\n$sth-&gt;execute(\"Matt\", \"Smith\", \"matt.smith@bar.com\");\n$sth-&gt;execute(\"Matt\", \"Brown\", \"matt.brown@baz.com\");\n\n# Select data from the database\n$sth = $dbh-&gt;prepare(\"SELECT first_name, surname, email FROM contacts WHERE first_name = ?\");\n$sth-&gt;execute(\"Matt\");\n\n# Print out HTTP header\nprint \"Content-type: text\/html\\n\\n\";\n\nprint &lt;&lt;HTML_PAGE;\n&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;Database Test&lt;\/title&gt;\n&lt;\/head&gt;\n&lt;body&gt;\n&lt;h1&gt;Database Test&lt;\/h1&gt;\n&lt;table&gt;\n&lt;tr&gt;\n&lt;th&gt;First Name&lt;\/th&gt;\n&lt;th&gt;Surname&lt;\/th&gt;\n&lt;th&gt;Email&lt;\/th&gt;\n&lt;\/tr&gt;\nHTML_PAGE\n\n# Loop over database query results\nwhile( $row = $sth-&gt;fetchrow_hashref ) {  \nprint \"&lt;tr&gt;$row-&gt;{first_name}&lt;\/td&gt;\";  \nprint \"&lt;td&gt;$row-&gt;{surname}&lt;\/td&gt;\";  \nprint \"&lt;td&gt;$row-&gt;{email}&lt;\/td&gt;&lt;\/tr&gt;\";\n}\n\nprint &lt;&lt;HTML_PAGE;\n&lt;\/table&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;\nHTML_PAGE<\/pre>\n<p><\/br>Replace the example database name, username and password, save this script as <strong>database_test.cgi<\/strong> and upload it to the <strong>cgi-bin<\/strong> on your web hosting. <strong>Make sure you set the file permissions for the script to 755 as described above<\/strong>.<\/p>\n<p>Now you&#8217;re ready to test your database script. Load up your database test in your browser, http:\/\/www.domain.com\/cgi-bin\/database_test.cgi. If everything works you should see a html page show a table of contacts. If not, try checking out our guides below.<\/p>\n<ul>\n<li><a href=\"https:\/\/www.lcn.com\/support\/articles\/troubleshooting-common-perl-issues\/\" target=\"_blank\" rel=\"noopener noreferrer\">Troubleshooting common Perl issues<\/a><\/li>\n<li><a href=\"https:\/\/www.lcn.com\/support\/articles\/how-to-create-an-email-form-with-perl\/\" target=\"_blank\" rel=\"noopener noreferrer\">How to create an email form with Perl<\/a><\/li>\n<li><a href=\"https:\/\/www.lcn.com\/support\/articles\/how-to-create-a-perl-script\/\" target=\"_blank\" rel=\"noopener noreferrer\">How to create a Perl script<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Connecting to a database is a very common task for cgi scripts but it can be a very involved process. Below we&#8217;ll step through connecting to, inserting into and querying a database and displaying back the results. Connecting to the database If you haven&#8217;t already created a MySQL database you can follow the How to [&hellip;]<\/p>\n","protected":false},"author":1,"comment_status":"closed","ping_status":"open","template":"","format":"standard","meta":{"footnotes":""},"ht-kb-category":[15],"ht-kb-tag":[5],"class_list":["post-110","ht_kb","type-ht_kb","status-publish","format-standard","hentry","ht_kb_category-creating-a-new-website","ht_kb_tag-web-hosting"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.2 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>How to use a database with Perl - LCN.com<\/title>\n<meta name=\"description\" content=\"How to use a database with Perl at LCN.comFollow this simple guide on how to connect, query and insert records into a database with Perl scripts.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-perl\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to use a database with Perl - LCN.com\" \/>\n<meta property=\"og:description\" content=\"How to use a database with Perl at LCN.comFollow this simple guide on how to connect, query and insert records into a database with Perl scripts.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-perl\/\" \/>\n<meta property=\"og:site_name\" content=\"Customer Support Guides - LCN\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/lcndotcom\" \/>\n<meta property=\"article:modified_time\" content=\"2020-03-04T17:08:50+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.lcn.com\/support\/wp-content\/uploads\/support-facebook-feed.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:site\" content=\"@lcndotcom\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"6 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-perl\/\",\"url\":\"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-perl\/\",\"name\":\"How to use a database with Perl - LCN.com\",\"isPartOf\":{\"@id\":\"https:\/\/www.lcn.com\/support\/#website\"},\"datePublished\":\"2020-02-12T10:36:34+00:00\",\"dateModified\":\"2020-03-04T17:08:50+00:00\",\"description\":\"How to use a database with Perl at LCN.comFollow this simple guide on how to connect, query and insert records into a database with Perl scripts.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-perl\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-perl\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-perl\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.lcn.com\/support\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"How to use a database with Perl\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.lcn.com\/support\/#website\",\"url\":\"https:\/\/www.lcn.com\/support\/\",\"name\":\"Customer Support Guides - LCN\",\"description\":\"- LCN\",\"publisher\":{\"@id\":\"https:\/\/www.lcn.com\/support\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.lcn.com\/support\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.lcn.com\/support\/#organization\",\"name\":\"LCN.com\",\"url\":\"https:\/\/www.lcn.com\/support\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.lcn.com\/support\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.lcn.com\/support\/wp-content\/uploads\/2020\/02\/ZF_-hcc3.jpg\",\"contentUrl\":\"https:\/\/www.lcn.com\/support\/wp-content\/uploads\/2020\/02\/ZF_-hcc3.jpg\",\"width\":461,\"height\":461,\"caption\":\"LCN.com\"},\"image\":{\"@id\":\"https:\/\/www.lcn.com\/support\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/lcndotcom\",\"https:\/\/x.com\/lcndotcom\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to use a database with Perl - LCN.com","description":"How to use a database with Perl at LCN.comFollow this simple guide on how to connect, query and insert records into a database with Perl scripts.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-perl\/","og_locale":"en_US","og_type":"article","og_title":"How to use a database with Perl - LCN.com","og_description":"How to use a database with Perl at LCN.comFollow this simple guide on how to connect, query and insert records into a database with Perl scripts.","og_url":"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-perl\/","og_site_name":"Customer Support Guides - LCN","article_publisher":"https:\/\/www.facebook.com\/lcndotcom","article_modified_time":"2020-03-04T17:08:50+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/www.lcn.com\/support\/wp-content\/uploads\/support-facebook-feed.jpg","type":"image\/jpeg"}],"twitter_card":"summary_large_image","twitter_site":"@lcndotcom","twitter_misc":{"Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-perl\/","url":"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-perl\/","name":"How to use a database with Perl - LCN.com","isPartOf":{"@id":"https:\/\/www.lcn.com\/support\/#website"},"datePublished":"2020-02-12T10:36:34+00:00","dateModified":"2020-03-04T17:08:50+00:00","description":"How to use a database with Perl at LCN.comFollow this simple guide on how to connect, query and insert records into a database with Perl scripts.","breadcrumb":{"@id":"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-perl\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-perl\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-perl\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.lcn.com\/support\/"},{"@type":"ListItem","position":2,"name":"How to use a database with Perl"}]},{"@type":"WebSite","@id":"https:\/\/www.lcn.com\/support\/#website","url":"https:\/\/www.lcn.com\/support\/","name":"Customer Support Guides - LCN","description":"- LCN","publisher":{"@id":"https:\/\/www.lcn.com\/support\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.lcn.com\/support\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.lcn.com\/support\/#organization","name":"LCN.com","url":"https:\/\/www.lcn.com\/support\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.lcn.com\/support\/#\/schema\/logo\/image\/","url":"https:\/\/www.lcn.com\/support\/wp-content\/uploads\/2020\/02\/ZF_-hcc3.jpg","contentUrl":"https:\/\/www.lcn.com\/support\/wp-content\/uploads\/2020\/02\/ZF_-hcc3.jpg","width":461,"height":461,"caption":"LCN.com"},"image":{"@id":"https:\/\/www.lcn.com\/support\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/lcndotcom","https:\/\/x.com\/lcndotcom"]}]}},"_links":{"self":[{"href":"https:\/\/www.lcn.com\/support\/wp-json\/wp\/v2\/ht-kb\/110","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.lcn.com\/support\/wp-json\/wp\/v2\/ht-kb"}],"about":[{"href":"https:\/\/www.lcn.com\/support\/wp-json\/wp\/v2\/types\/ht_kb"}],"author":[{"embeddable":true,"href":"https:\/\/www.lcn.com\/support\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.lcn.com\/support\/wp-json\/wp\/v2\/comments?post=110"}],"version-history":[{"count":1,"href":"https:\/\/www.lcn.com\/support\/wp-json\/wp\/v2\/ht-kb\/110\/revisions"}],"predecessor-version":[{"id":438,"href":"https:\/\/www.lcn.com\/support\/wp-json\/wp\/v2\/ht-kb\/110\/revisions\/438"}],"wp:attachment":[{"href":"https:\/\/www.lcn.com\/support\/wp-json\/wp\/v2\/media?parent=110"}],"wp:term":[{"taxonomy":"ht_kb_category","embeddable":true,"href":"https:\/\/www.lcn.com\/support\/wp-json\/wp\/v2\/ht-kb-category?post=110"},{"taxonomy":"ht_kb_tag","embeddable":true,"href":"https:\/\/www.lcn.com\/support\/wp-json\/wp\/v2\/ht-kb-tag?post=110"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}