<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;homepageUrl=http%3A%2F%2Fwww.danshope.com%2Fblog%2F&amp;blogLocale=en_US&amp;searchRoot=http%3A%2F%2Fblogsearch.google.com%2F" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" height="30px" width="100%" id="navbar-iframe" 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: , , , , , ,


Friday, December 5, 2008

MySQL Engine Wars: InnoDB vs MyISAM

This isn’t a post to start the flame wars between the MyISAM and InnoDB camps, it’s just a short blurb to list some facts about both and let you hash it out in the comments. For those of you not in the know, two of the widely used MySQL database engines (engines control how the data is stored and accessed) are MyISAM and InnoDB, both which have their niche. If you look this up online, there’s a whole lot of discussion about “which is better”, but there’s not really one overall metric that sums up either engine. 

I was going to write a little guide with a table comparison of different features such as row locking, key constraints, and full text indexing, but I came across this great post over at Tag1 Consulting. Hop on over for a good read about the differences between the two engines and when it is appropriate to choose one over the other.

MyISAM vs. InnoDB @ Tag1 Consulting

Labels: , , , ,


Wednesday, December 3, 2008

MySQL & PHP: Connecting and Transferring Data

In previous posts I’ve covered a general overview of how SQL and PHP work together and the benefits of creating dynamic content. We have discussed content management systems and how they can simplify your life as a webmaster. Now we’ll start to look at how to actually construct a content management system, starting with connecting PHP to MySQL. 

First, we need to establish a connection using the builtin PHP function, “mysqli_connect”. The old PHP functions for MySQL communication have been outdated by the new “mysqli” family of functions. The standard functions haven’t  been deprecated, so you can still use them, but the added functionality of the “mysqli” group is very useful to have. 

Let’s set up an example where we connect to a MySQL database and pull out the member names, just like in the other examples. For clarity’s sake I’ll use the standard SQL functions instead of regular expressions. 


<?php

 //declare a global variable for database interaction (can be called by any function)
global $mysqli;

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

//if connection fails, stop script execution
if (mysqli_connect_errno()) {
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit();

//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);

?>

When using this code, you will need to fill in “username” and “password” with the actual values you have set up for your database. It is bad practice to use the root account for this, as any script would have administrative access. Instead, set up another account that only has SELECT, INSERT, and UPDATE privileges. 

In the (while) loop we are pulling the data out of an array we construct from the record that MySQL returns based on our query. We then echo or print to screen the information so we can verify the script is working. Notice the break (
) tags inside the echo line – we are embedding HTML tags in PHP scripts. The other parts of the notation enable us to string together strings and variables. When the final print out is made, we will have something like the following:

Last Name: Falwell
First Name: James
Email: jfalwell@gmail.com

Last Name: Farney
First Name: Sarah Marie
Email: sarah_baby@msn.net

….

Last Name: Flaherty
First Name: Timothy
Email: tflaherty@salvationarmy.org

Pretty neat huh? We can use similar code to insert data into the database. The main code that we will reuse is the connection code, so perhaps we should make it modular and stick it into its own function. Next time I’ll show you how to make a login console that you can access from everywhere on your site and connect to different databases or using different logins! We’ll also discuss the php include() directive and how to make your page code modular to save space and leverage the power of the PHP scripting language.

Labels: , , , , , ,


Monday, December 1, 2008

Quick MySQL Reference Sheet

As promised here is a quick guide to some of the most frequently used commands in any SQL environment. You can find a more detailed description in the introduction to relational databases. 

Commands are not case-sensitive - they do not need to be capitalized. It's common practice to use all caps for commands so that dynamic data (table names, inserted values) can be noticed with ease.

  • CREATE Command - is used to create a database/table.
  • SELECT Command - is used to retrieve data from the database.
  • DELETE Command - is used to delete data from the database.
  • INSERT Command - is used to insert data into a database.
  • UPDATE Command - is used to update the data in a table.
  • DROP Command - is used to delete or drop the database/table.

 Syntax for Query Commands

CREATE Command
The Create command is used to create a table by specifying the tablename, fieldnames and constraints as shown below:

Syntax:

mysql> CREATE TABLE tablename;

Example:

mysql> CREATE TABLE tblstudent(fldstudid int(10) NOTNULL AUTO_INCREMENT PRIMARY KEY,fldstudName VARCHAR(250) NOTNULL,fldstudentmark int(4) DEFAULT '0' ;

SELECT Command
The Select command is used to select the records from a table using its field names. To select all the fields in a table, '*' is used in the command. The result is assigned to a variable name as shown below:

Syntax:

mysql> SELECT field_names FROM tablename;

Example:

mysql> SELECT * FROM tblstudent;

DELETE Command
The Delete command is used to delete the records from a table using conditions as shown below:

Syntax:

mysql> DELETE * FROM tablename WHERE condition;

Example:

mysql> DELETE * FROM tblstudent WHERE fldstudid=2";

INSERT Command
The Insert command is used to insert records into a table. The values are assigned to the field names as shown below:

Syntax:

mysql> INSERT INTO tablename(fieldname1,fieldname2..) VALUES(value1,value2,...) ;

Example:

mysql> INSERT INTO Tblstudent(fldstudName,fldstudmark) VALUES(Baskar,75) ;

UPDATE Command
The Update command is used to update the field values using conditions. This is done using 'SET' and the fieldnames to assign new values to them.

Syntax:

mysql> UPDATE Tablename SET (fieldname1=value1,fieldname2=value2,...) WHERE fldstudid=IdNumber;

Example:

mysql> UPDATE Tblstudent SET (fldstudName=siva,fldstudmark=100) WHERE fldstudid=2;

DROP Command
The Drop command is used to delete all the records in a table using the table name as shown below:

Syntax:

mysql> DROP tablename;

Example:

mysql> DROP tblstudent;

Labels: , , , ,



A Simple Guide to Constructing Advanced SQL Queries

Last time we defined the meaning of a database and picked apart a few examples queries from the MySQL camp. To recap, we looked at CREATE TABLE, INSERT, UPDATE, ALTER TABLE, and SELECT statements. Just to refresh your memory, they use the following syntax (abbreviated listing): 

SELECT a, list, of, stuff  FROM tablename

ALTER TABLE tablename ADD name datatype other_parameters

UPDATE tablename SET colname = somevalue WHERE somecolumn = ‘some_value’

INSERT INTO tablename (list, of, colnames) VALUES (‘list’, ‘of’, ‘values’)

CREATE TABLE (colname_1 datatype, colname_2 datatype, …colname_N datatype

These are just a few of the basic commands or queries that are typically executed on a daily basis. Create Table is a little rarer in an established application since we are focusing on getting data into and out of an existing database. Applications that must dynamically create a database every run time are a niche product and do not represent typical behavior.

SQL Search Engine
Let’s say you want to make a SQL search engine that pulls data out from our members database. Suppose we want to generate a listing of all of the members, sorted alphabetically. We could construct the following query: 

mysql> SELECT * FROM members ORDER BY lastname ASC;

This will pull all of the data about each member and return a list that is sorted from A to Z. If we want the data returned from Z to A we would specify DESC (descending) after ORDER BY instead of ASC (ascending). At a minimum SQL will let you sort by an integer column, alphabetical (VARCHAR or TEXT), decimal or floating point, and date columns. Since the SQL engine doesn’t know the lexical ordering of raw binary data, BLOB columns aren’t typically sorted. Even TEXT columns, since they have an “unlimited” length, will only sort up to X amount of characters (this value can be changed at the cost of system efficiency). 

Grouping the Data
Well, that was fine and dandy, but I have over 25,000 members and that’s just too large of a list. Perhaps we could break it down a little more, let’s say by letter. We want to be able to create an interface like that below, where we can click on a letter and get all of the last names that begin with that letter, sorted alphabetically to return the following results:

A B C D E F G H I J K L M N O P Q R S T U V W X Y

Name                                      Email

Falwell, James                         jfalwell@gmail.com

Farney, Sarah Marie                sarah_baby@msn.net

Fardwood, Alexandra             cutsiepie99@hotmail.com

Fickleton, Martin                    martin_fickleton@cnn.com

Fiduciary, Dixon                     fdixon@gatech.edu

Fixington, Thomas                  thomas-the-tank@gmail.com

Flaherty, Timothy                   tflaherty@salvationarmy.org

We would construct the query:

mysql> SELECT lastname, firstname, email FROM members WHERE lastname LIKE “F%”;

 The syntax used here is a call to a SQL function “LIKE” that can take parameters such as the “F” and “%”. The % is a wildcard that matches any number of characters. There are different wildcards that can match single characters, or a specified number of characters. 

Perhaps you want a more advanced engine than can find parts of words (substrings) inside a given column. We can modify the above example by adding a “%” before the letter. 

mysql> SELECT lastname, firstname, email FROM members WHERE lastname LIKE “%F%”; 

Now we will get any and all members that have an “F” somewhere in their last name. The wildcards just say “find an f” even if there are letters to the left or right. Notice that % matches zero or more characters – the search will still return the members who’s last names begin with “F”.

Regular Expressions
If you want to do even more advanced searches you can use regular expressions. Regular expressions provide a concise and flexible means for identifying strings of text of interest, such as particular characters, words, or patterns of characters. Regular expressions are written in a formal language that can be interpreted by a regular expression processor, a program that either serves as a parser generator or examines text and identifies parts that match the provided specification. They can be very complex or very simple – returning results such as those above, or employed in an advanced data processing suite. Regular expressions are not SQL based, they are used in almost every developed programming language available. 

Regex based searches are generally very efficient and can be optimized for speed by an advanced programmer. As with most programming paradigms, there are many ways to employ regex strings to attack any one problem. There are “best-practices” to follow when using regular expressions, but in general you need to become familiar with the technology and syntax before you start optimizing statements. 

As exemplified by this XKCD comic, regular expressions are a very powerful tool that you will make you wonder what you ever did without them. Now, it’s not absolutely required that you start using regular expressions right now; in fact, it’s probably better for you to get accustomed to the SQL syntax before delving into this more complex topic. That being said, I’ll show you a few quick examples of what regex searches can do for you! 

Let’s start with the example above. We wanted to find all members whose last names started with the letter “F”. To make this into a regular expression based search, we’d simply type the following. 

mysql> SELECT lastname, firstname, email FROM members WHERE lastname REGEXP “^F”; 

or to be more explicit, 

mysql> SELECT lastname, firstname, email FROM members WHERE lastname REGEXP “^F.+$”;

If we break down the search string “^F” we have two components, the letter we are searching by and some other character “^”. This character just tells the regex engine to start looking at the beginning of the word. If we would omit the “^” we would get all results that had an “F” anywhere in the lastname column. 

The second example adds a few more characters that explicitly define our search as “starting at the beginning of the last name, search for an F and any other characters until the end.” The dollar sign “$” is a tag for the end of the string. “.+” just represents any number of any characters. The “.” specifier matches any character, including numbers and whitespaces, while the “+” symbol says to apply the previous specifier to any number of characters.

 This is a very basic example of regular expressions and the syntax used in more advanced SQL queries. I’ll be posting a simple table guide later so you don’t have to wade through an entire post to get the information you need! Let me know your thoughts in the comments!

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