<body bgcolor=#000033"><script type="text/javascript"> function setAttributeOnload(object, attribute, val) { if(window.addEventListener) { window.addEventListener("load", function(){ object[attribute] = val; }, false); } else { window.attachEvent('onload', function(){ object[attribute] = val; }); } } </script> <iframe src="http://www.blogger.com/navbar.g?targetBlogID=4830160160028833890&amp;blogName=DanShope.com&amp;publishMode=PUBLISH_MODE_FTP&amp;navbarType=BLUE&amp;layoutType=CLASSIC&amp;searchRoot=http%3A%2F%2Fblogsearch.google.com%2F&amp;blogLocale=en_US&amp;homepageUrl=http%3A%2F%2Fwww.danshope.com%2Fblog%2F" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" height="30px" width="100%" id="navbar-iframe" allowtransparency="true" title="Blogger Navigation and Search"></iframe> <div></div>

Thursday, December 11, 2008

Using PHP include() to Create a MySQL Login

Last time we looked at connecting and transferring data between MySQL and PHP, but it was all in one file. In practice, we need to separate the “calling” code and the login code so that if our login information ever changes, we only have to update it in one place. This is also more secure as we can store the do_login function in a secure directory, instead of having the username and passwords stored in large number of files and directories. 

The first file we’ll need to create is do_login.php (see below). We’ll reference this file in every page that needs access to the database. It’s the same code as I used before, with a few changes. First, the code is wrapped in a function doDB, so that we can call it from our page code. I also added a parameter called $data_name so that we can pass in a particular database. 

This can be very useful if you are using multiple databases, such as one for Members, Books, News…etc. If we didn’t use this parameterized function we’d need a different do_login file for each different database, which uses more file space and requires more maintenance. 

do_login.php

<?php 

//set up a database login function
function doDB($data_name) {

            global $mysqli;

            //connect to server and select database; you may need it
            $mysqli = mysqli_connect("localhost", "username", "password", $data_name);

            //if connection fails, stop script execution             if (mysqli_connect_errno()) {

                        printf("Connect failed: %s\n", mysqli_connect_error());

                        exit();
            }

}

?>p;

This file alone is pretty useless as it just attempts to establish a connection to the database and gives an error if it’s unsuccessful. We need to attach this file to our other code – the worker code that retrieves data from the Members database. 

memberlist.php

<?php

//recall the do_login file
include($_SERVER['DOCUMENT_ROOT']."/resource/do_login.php");

//make the connection using the function call doDB
doDB("memberDB");

//get member information
$get_data_sql = "SELECT lastname, firstname, email FROM members WHERE lastname LIKE “F%”;

//get the data or exit if there is an error
$get_data_res = mysqli_query($mysqli, $get_data_sql) or die(mysqli_error($mysqli));

while ($member_info = mysqli_fetch_array($get_data_res)) {
            $lastN = $member_info['lastname'];
            $firstN = $member_info['firstname'];
            $email = $member_info['email'];

echo “Last Name: “.$lastN.”First Name: “.$firstN.”Email: “.$email.”;

}

//close connection to MySQL
mysqli_close($mysqli);

?>

The last 2/3 of this code should be pretty familiar – it’s the same as the previous memberlist code we looked at last time. The big change is at the top. The line 

include($_SERVER['DOCUMENT_ROOT']."/resource/do_login.php"); 

uses an in-built php function “include” that just says – take the file inside the parentheses and paste it into this document.” The include directive pulls in the specified file and treats it like a text file. If you could see the php code after this include statement is executed it would look something like (some code omitted): 

<?php
//set up a database login function function doDB($data_name) {

            global $mysqli;             //connect to server and select database; you may need it

……….

//make the connection using the function call doDB
doDB("memberDB");

//get member information
……….

?>

Congratulations! Now you know how to connect files in PHP using the include() function. You’ve also seen a function call – doDB(“memberDB”) calls the function doDB, which in turn attempts to establish a connection the the database memberDB. You can use this code from anywhere on your site – the $_SERVER[‘DOCUMENT_ROOT’] part ensures that PHP starts looking for your file from the domain root (www/).

This same strategy can be employed to load static headers and footers on each of your webpage so that navigation only has to updated in one place! If you want to dynamically load the title into each webpage, all you have to do is pass a $title parameter to the function you write! It’s really that simple, and you’ll be on your way to mastering PHP.

Labels: , , , , , ,


Subscribe to RSS Feed
Subscribe to DanShope.com
Who writes This Stuff?
Daniel Shope is the site owner and moderator of DanShope.com, a portal dedicated to robotics and engineering. Dan is currently a student at Carnegie Mellon University and is pursuing dual degrees in Mechanical and Biomedical engineering.

View Daniel Shope's profile on LinkedIn
Advertisements