{"id":111,"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-php\/"},"modified":"2020-03-05T13:33:09","modified_gmt":"2020-03-05T13:33:09","slug":"how-to-use-a-database-with-php","status":"publish","type":"ht_kb","link":"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-php\/","title":{"rendered":"How to use a database with PHP"},"content":{"rendered":"\n<p>Using a database is a very common task for PHP scripts but it can be a very involved process. Below we&#8217;ll step through connecting to, inserting records and querying a database and displaying back the results.<\/p>\n<p>PHP has many predefined functions for dealing with MySQL databases, you can find a full description of these at: <a href=\"http:\/\/php.net\/manual\/en\/book.mysqli.php\" target=\"blank\" rel=\"noopener noreferrer\">http:\/\/php.net\/manual\/en\/book.mysqli.php<\/a>.<\/p>\n<h3>Your database details<\/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 <i>DB_name<\/i>, remember to replace this with your actual database name.<\/p>\n<h3>Connecting to the database<\/h3>\n<pre class=\"prettyprint linenums lang-php\">&lt;?php<br \/>$connection = mysqli_connect(\"database4.lcn.com\", \"DB_username\", \"DB_password\", \"DB_name\");<br \/><br \/>if (!$connection) {<br \/>echo \"Error: Unable to connect to MySQL.\" . PHP_EOL;<br \/>exit;<br \/>}<\/pre>\n<\/br><p><strong>Lines 1-2<\/strong> &#8211; Creates a connection to our database using mysqli_connect including parameters for: the database hostname, username, password and database name. A reference to our database connection is now stored in the $connection variable \u2013 which we&#8217;ll use next to perform some actions on our database. The fields for &#8220;database4.lcn.com&#8221; &#8220;DB_username&#8221;, &#8220;DB_password&#8221; and &#8220;DB_name&#8221; should be updated to include your database hostname, username, password and database name.<\/p>\n<p><strong>Lines 4-6<\/strong> &#8211; If we couldn&#8217;t connect for any reason an error message is returned.<\/p>\n<p>\u00a0<\/p>\n<h3>Creating a database table<\/h3>\n<p>Databases organise their records into tables. Each table should only contain one type of information.<\/p>\n<p>In this example we&#8217;ll create a simple table to store contact information that hold First Name, Last Name and Email Address.<\/p>\n<pre class=\"prettyprint linenums lang-php\">&lt;?php<br \/>$sql = \"CREATE TABLE IF NOT EXISTS Contacts (<br \/>FirstName varchar(64),<br \/>LastName varchar(64),<br \/>EmailAddress varchar(255))\";<br \/><br \/>mysqli_query($connection, $sql);<br \/><br \/>?&gt;<\/pre>\n<\/br><p><strong>Lines 2-5<\/strong> &#8211; Store a SQL query that will create our contacts table. We&#8217;ve declared <i>FirstName<\/i> and <i>LastName<\/i> as VARCHARs (variable characters, which is what we usually use for short text) with a length of 64 characters which should work for some pretty long names, and <i>EmailAddress<\/i> as a VARCHAR with a length of 255 characters, as Email Addresses can be quite long.<\/p>\n<p><strong>Line 8<\/strong> &#8211; Will run our SQL query on the database, and create our table.<\/p>\n<h3>Inserting Records into our new table<\/h3>\n<p>Our next step is to start filling our table with information.<\/p>\n<pre class=\"prettyprint linenums lang-php\">mysqli_query($connection, \"INSERT INTO Contacts (FirstName, LastName, EmailAddress)<br \/>VALUES ('Peter', 'Griffin', 'peter@thehappygoluckytoyfactory.com')\");<br \/><br \/>mysqli_query($connection, \"INSERT INTO Contacts (FirstName, LastName, EmailAddress)<br \/>VALUES ('Homer', 'Simpson', 'homer@springfieldpowerplant.com')\");<br \/><br \/>mysqli_query($connection, \"INSERT INTO Contacts (FirstName, LastName, EmailAddress)VALUES ('Philip', 'Fry', 'pjfry@planetexpress.com')\");<\/pre>\n<\/br><p>This code will insert 3 records into our <i>Contacts<\/i> table. Now that we have some data, we&#8217;ll take a look at how we look up and fetch data from our table.<\/p>\n<h3>Querying our database<\/h3>\n<p>We&#8217;re now going to find all the records from our <i>Contacts<\/i> table that have the <i>FirstName<\/i> &#8220;Peter&#8221;.<\/p>\n<pre class=\"prettyprint linenums lang-php\">$results = mysqli_query($connection, \"SELECT FirstName, LastName, EmailAddress FROM Contacts WHERE FirstName='Peter'\");<\/pre>\n<\/br><p>This code will put an Array containing the <i>FirstName<\/i>, <i>LastName<\/i> and <i>EmailAddress<\/i> fields from records with a <i>FirstName<\/i> of &#8216;Peter&#8217; into the variable <i>$results<\/i>.<\/p>\n<h3>Displaying our results<\/h3>\n<p>We&#8217;re now going to print our results into an HTML table.<\/p>\n<pre class=\"prettyprint linenums lang-php\">echo \"&lt;table border='1'&gt;<br \/>&lt;tr&gt;<br \/>&lt;th&gt;FirstName&lt;\/th&gt;<br \/>&lt;th&gt;LastName&lt;\/th&gt;<br \/>&lt;th&gt;EmailAddress&lt;\/th&gt;<br \/>&lt;\/tr&gt;\";<br \/><br \/>while($row = mysqli_fetch_array($results)) {<br \/>echo \"&lt;tr&gt;\";<br \/>echo \"&lt;td&gt;\" . $row['FirstName'] . \"&lt;\/td&gt;\"; <br \/>echo \"&lt;td&gt;\" . $row['LastName'] . \"&lt;\/td&gt;\"; <br \/>echo \"&lt;td&gt;\" . $row['EmailAddress'] . \"&lt;\/td&gt;\"; <br \/>echo \"&lt;\/tr&gt;\"; <br \/>}<br \/>echo \"&lt;\/table&gt;\";<\/pre>\n<\/br><p><strong>Lines 1-6<\/strong> &#8211; Begins our table and creates some headings for our table.<\/p>\n<p><strong>Lines 8-15<\/strong> &#8211; Loop over each of our results, and prints out a new row in our table.<\/p>\n<p><strong>Line 16<\/strong> &#8211; Closes our table.<\/p>\n<h3>Disconnecting from the database<\/h3>\n<pre class=\"prettyprint linenums lang-php\">mysqli_close($connection);<\/pre>\n<\/br><p>It&#8217;s important that we make sure to close our connection to the database at the end of our script, so that we don&#8217;t end up leaving connections open. Having a lot of unclosed connections can cause issues.<\/p>\n<h3>The final script<\/h3>\n<pre class=\"prettyprint linenums lang-php\">&lt;?php<br \/>\/\/ Connect to the database<br \/><br \/>$connection = mysqli_connect(\"database4.lcn.com\", \"LCN345596_db\", \"terminal1\", \"ranoutofideas_com_db\");<br \/><br \/>if (!$connection) {<br \/>echo \"Error: Unable to connect to MySQL.\" . PHP_EOL;    <br \/>exit;<br \/>}<br \/><br \/>\/\/ Create our table<br \/><br \/>$sql = \"CREATE TABLE IF NOT EXISTS Contacts (<br \/>FirstName varchar(64),<br \/>LastName varchar(64),<br \/>EmailAddress varchar(255))\";<br \/><br \/>mysqli_query($connection, $sql);<br \/><br \/>\/\/ Insert some records<br \/><br \/>mysqli_query($connection, \"INSERT INTO Contacts (FirstName, LastName, EmailAddress)VALUES ('Peter', 'Griffin', 'peter@thehappygoluckytoyfactory.com')\");<br \/><br \/>mysqli_query($connection, \"INSERT INTO Contacts (FirstName, LastName, EmailAddress)VALUES ('Homer', 'Simpson', 'homer@springfieldpowerplant.com')\");<br \/><br \/>mysqli_query($connection, \"INSERT INTO Contacts (FirstName, LastName, EmailAddress)VALUES ('Philip', 'Fry', 'pjfry@planetexpress.com')\");<br \/><br \/>\/\/ Query our Database<br \/><br \/>$results = mysqli_query($connection, \"SELECT FirstName, LastName, EmailAddress FROM Contacts WHERE FirstName='Peter'\");<br \/><br \/>\/\/ Print out our results<br \/><br \/>echo \"&lt;table border='1'&gt;<br \/>&lt;tr&gt;<br \/>&lt;th&gt;FirstName&lt;\/th&gt;<br \/>&lt;th&gt;LastName&lt;\/th&gt;<br \/>&lt;th&gt;EmailAddress&lt;\/th&gt;<br \/>&lt;\/tr&gt;\";<br \/><br \/>while($row = mysqli_fetch_array($results))<br \/>{<br \/>echo \"&lt;tr&gt;\"; <br \/>echo \"&lt;td&gt;\" . $row['FirstName'] . \"&lt;\/td&gt;\"; <br \/>echo \"&lt;td&gt;\" . $row['LastName'] . \"&lt;\/td&gt;\"; <br \/>echo \"&lt;td&gt;\" . $row['EmailAddress'] . \"&lt;\/td&gt;\"; <br \/>echo \"&lt;\/tr&gt;\"; <br \/>}<br \/>echo \"&lt;\/table&gt;\";<br \/><br \/>\/\/ Close our connection to the database<br \/><br \/>mysqli_close($connection);<br \/><br \/>?&gt;<\/pre>\n<\/br><p>That&#8217;s it! You now have all you need to use a database with PHP.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Using a database is a very common task for PHP scripts but it can be a very involved process. Below we&#8217;ll step through connecting to, inserting records and querying a database and displaying back the results. PHP has many predefined functions for dealing with MySQL databases, you can find a full description of these at: [&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-111","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 PHP - LCN.com<\/title>\n<meta name=\"description\" content=\"How to use a database with PHP at LCN.comFollow this simple guide on how to connect, query and insert records into a database with PHP 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-php\/\" \/>\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 PHP - LCN.com\" \/>\n<meta property=\"og:description\" content=\"How to use a database with PHP at LCN.comFollow this simple guide on how to connect, query and insert records into a database with PHP scripts.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-php\/\" \/>\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-05T13:33:09+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=\"5 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-php\/\",\"url\":\"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-php\/\",\"name\":\"How to use a database with PHP - LCN.com\",\"isPartOf\":{\"@id\":\"https:\/\/www.lcn.com\/support\/#website\"},\"datePublished\":\"2020-02-12T10:36:34+00:00\",\"dateModified\":\"2020-03-05T13:33:09+00:00\",\"description\":\"How to use a database with PHP at LCN.comFollow this simple guide on how to connect, query and insert records into a database with PHP scripts.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-php\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-php\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-php\/#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 PHP\"}]},{\"@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 PHP - LCN.com","description":"How to use a database with PHP at LCN.comFollow this simple guide on how to connect, query and insert records into a database with PHP 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-php\/","og_locale":"en_US","og_type":"article","og_title":"How to use a database with PHP - LCN.com","og_description":"How to use a database with PHP at LCN.comFollow this simple guide on how to connect, query and insert records into a database with PHP scripts.","og_url":"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-php\/","og_site_name":"Customer Support Guides - LCN","article_publisher":"https:\/\/www.facebook.com\/lcndotcom","article_modified_time":"2020-03-05T13:33:09+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":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-php\/","url":"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-php\/","name":"How to use a database with PHP - LCN.com","isPartOf":{"@id":"https:\/\/www.lcn.com\/support\/#website"},"datePublished":"2020-02-12T10:36:34+00:00","dateModified":"2020-03-05T13:33:09+00:00","description":"How to use a database with PHP at LCN.comFollow this simple guide on how to connect, query and insert records into a database with PHP scripts.","breadcrumb":{"@id":"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-php\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-php\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.lcn.com\/support\/articles\/how-to-use-a-database-with-php\/#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 PHP"}]},{"@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\/111","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=111"}],"version-history":[{"count":2,"href":"https:\/\/www.lcn.com\/support\/wp-json\/wp\/v2\/ht-kb\/111\/revisions"}],"predecessor-version":[{"id":1373,"href":"https:\/\/www.lcn.com\/support\/wp-json\/wp\/v2\/ht-kb\/111\/revisions\/1373"}],"wp:attachment":[{"href":"https:\/\/www.lcn.com\/support\/wp-json\/wp\/v2\/media?parent=111"}],"wp:term":[{"taxonomy":"ht_kb_category","embeddable":true,"href":"https:\/\/www.lcn.com\/support\/wp-json\/wp\/v2\/ht-kb-category?post=111"},{"taxonomy":"ht_kb_tag","embeddable":true,"href":"https:\/\/www.lcn.com\/support\/wp-json\/wp\/v2\/ht-kb-tag?post=111"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}