07-09-2016, 10:50 AM
1453436210-PHPandMySQL.doc (Size: 429 KB / Downloads: 32)
Introduction
On the Web today, content is king. After you've mastered HTML and learned a few neat tricks in JavaScript and Dynamic HTML, you can probably build a pretty impressive-looking Web site design. But then comes the time to fill that fancy page layout with some real information. Any site that successfully attracts repeat visitors has to have fresh and constantly updated content. In the world of traditional site building, that means HTML files--and lots of 'em.
The problem is that, more often than not, the people providing the content for a site are not the same people handling its design. Oftentimes, the content provider doesn't even know HTML. How, then, is the content to get from the provider onto the Web site? Not every company can afford to staff a full-time Webmaster, and most Webmasters have better things to do than copying Word files into HTML templates anyway.
Maintenance of a content-driven site can be a real pain, too. Many sites (perhaps yours?) feel locked into a dry, outdated design because rewriting those hundreds of HTML files to reflect a new design would take forever. Server-side includes (SSI's) can help alleviate the burden a little, but you still end up with hundreds of files that need to be maintained should you wish to make a fundamental change to your site.
The solution to these headaches is database-driven site design. By achieving complete separation between your site's design and the content you are looking to present, you can work with each without disturbing the other. Instead of writing an HTML file for every page of your site, you only need to write a page for each kind of information you want to be able to present. Instead of endlessly pasting new content into your tired page layouts, create a simple content management system that allows the writers to post new content themselves without a lick of HTML!
In this 10-part weekly series of articles, I'll provide a hands-on look at what's involved in building a database-driven Web site. We'll be using two new tools for this: the PHP scripting language and the MySQL relational database. If your Web host provides PHP/MySQL support, you're in great shape. If not, we'll be looking at the set-up procedures under Unix and Windows, so don't sweat it.
These articles are aimed at intermediate or advanced Web designers looking to make the leap into server-side programming. You'll be expected to be comfortable with HTML, as I'll be making use of it without explanation. A teensy bit of JavaScript may serve us well at some point, but I'll be sure to keep it simple for the uninitiated.
By the end of this series, you can expect to have a grasp of what's involved in setting up and building a database-driven Web site. If you follow along with the examples, you'll also learn the basics of PHP (a server-side scripting language that allows you to do a lot more than access a database easily) and Structured Query Language (SQL -- the standard language for interacting with relational databases). Most importantly, you'll come away with everything you need to get started on your very own database-driven site in no time!
Installation
Welcome to the Show
Hi there, and welcome to the first in SitePoint.com's ten-part series on building a database-driven Web site! For the next few months, it will be my job to guide you as you take your first steps beyond the HTML-and-JavaScript world of client-side site design. Together we'll learn everything that's needed to build the kind of large, content-driven sites that are so successful today, but which can be a real headache to maintain if they aren't done right.
Before we get started, we need to gather together the tools we'll need for the job. In this first article, we'll download and set up the two software packages we'll be using: PHP and MySQL.
PHP is a server-side scripting language. You can think of it as a "plug-in" for your Web server that will allow it to do more than just send plain Web pages when browsers request them. With PHP installed, your Web server will be able to read a new kind of file (called a "PHP script") that can do things like retrieve up-to-the-minute information from a database and insert it into a Web page before sending it to the browser that requested it. PHP is completely free to download and use.
To retrieve information from a database, you first need to have a database. That's where MySQL comes in. MySQL is a relational database management system, or RDBMS. Exactly what role it plays and how it works we'll get into later, but basically it's a software package that is very good at organizing and managing large amounts of information. MySQL also makes that information really easy to get at using server-side scripting languages like PHP. MySQL is free for non-commercial use on most Unix-based platforms, like Linux. MySQL for Windows 9x/NT/2000 costs about US$200 to buy, but you can download an older version for free if you just want to try it out. For our purposes, the older version will serve just fine, but if you find MySQL for Windows useful and you decide to use it on one of your own sites, you should pay for it.
If you're lucky, your current Web host may already have installed MySQL and PHP on your Web server for you. If that's the case, much of this article will not apply to you, and you can skip straight to If Your Web Host Provides PHP and MySQL to make sure everything is ship shape.
Everything we'll discuss in this article series may be done on a Windows- or Unix-based server. Depending on which type of server you'll be using, the installation procedure will be different. The next section deals with installation on a Windows-based Web server. The section after that deals with installation under Linux (and other Unix-based platforms). Unless you're especially curious, you should only need to read the section that applies to you.
Installation under Windows
As I mentioned above, MySQL for Windows costs about US$200 to buy. For those of us who just want to try it out and see what it can do, T.c.X. (the company that develops MySQL) provides an older version that can be downloaded for free. It can be found by going to http://www.mysql (or one of its mirrors listed at http://www.mysqlmirrors.html) and selecting "Register and download shareware version of MySQL-Win32" in the "Downloads" section under "Downloads for Windows MySQL related software". After downloading the file, unzip it and run the setup.exe program contained therein.
Once installed, MySQL is ready to roll (barring a couple of configuration tasks that we'll look at shortly). Just like your Web server, MySQL is a server that should be run in the background so that it may respond to requests for information at any time. The server program may be found in the "bin" subfolder of the folder where you installed MySQL. If you are using the shareware version of MySQL, the server is called mysqld-shareware.exe. Before proceeding, rename this file to mysqld.exe. From the MS-DOS Prompt, start the server:
C:\mysql\bin> mysqld
To ensure that the server is started whenever Windows starts, you might want to create a shortcut to the program and put it in your Startup folder. If you decide to buy MySQL, it will come with a version that can be installed as a Windows NT/2000 service with the following command:
C:\mysql\bin> mysqld-nt --install
If you have trouble running the shareware version under Windows NT/2000, you can try running the server as a standalone program:
C:\mysql\bin> mysqld --standalone
The next step is to install PHP. At the time of this writing, PHP 4.0 was available as "Release Candidate 2"--or "almost ready but not quite". Personally I use PHP 4.0-RC2 and don't have any trouble with it. Since the final version is slated for release "real soon now" (likely before this series of articles is even finished), I'd recommend you install the latest version of 4.0 so you don't have to change anything when the final version is released.
PHP may be downloaded for free from http://www.php (or one of its mirrors listed at http://www.phpmirrors.php). You want the "binaries for Win32" package. Don't worry about grabbing any of the add-ons; we don't need them. A good installation guide for PHP 3.0 for Windows is available at the following URL: http://www.umesd.k12.or.us/php/win32install.html. It'll probably be updated with instructions for PHP 4.0 when it is finally released, but since installation of 4.0 is pretty much identical to installation of 3.0, you shouldn't have any trouble following the instructions with either version.
Don't worry about any of the optional steps (like choosing extension modules)-we'll work through those things together in a little bit. If you have any trouble following the instructions, feel free to post your question to the SitePoint.com Forums. I will be glad to help if the other helpful people there don't beat me to it!
With MySQL and PHP installed, you're ready to proceed to Post-Installation Setup Tasks.
Installing under Linux
This section covers the exact procedure for installing PHP and MySQL under RedHat Linux 5 or later. If you're using a different flavor of Linux, or another Unix-based operating system, the steps involved will be very similar, if not identical.
As a user of RedHat Linux, you may be tempted to download and install the RPM distributions of PHP and MySQL. RPM's are nice, pre-packaged versions of software that are really easy to install. Unfortunately, they also limit the options you have in choosing how the software is configured. For this reason, I consider the RPM versions of PHP and MySQL to be more trouble than they are worth.
Since a few of the default RedHat Linux install configurations will automatically install PHP for you, your first step should be to remove any old versions of PHP and MySQL from your system. You'll need to be logged in as the root user to issue the commands to do this. Note that in the following commands, "%" represents the shell prompt, and is not something that needs to be typed.
% rpm -e mysql
% rpm -e php
If either or both of these commands tell you that the program in question is not installed, don't worry about it. If the second command runs successfully (i.e. no message is displayed), then you did indeed have an older version of PHP installed, and you'll need to do one more thing to get rid of it entirely. Open your Apache configuration file (usually /etc/httpd/conf/httpd.conf) in your favorite text editor and look for the two lines shown here. They usually appear in separate sections of the file, so don't worry if they're not together.
LoadModule php3_module modules/libphp3.so
AddModule mod_php3.c
These lines are responsible for telling Apache to load PHP as a plug-in module. Since you just uninstalled that module, you'll need to get rid of these lines to make sure Apache keeps working properly. You can comment out these lines by adding a hash (#) at the beginning of both lines.
To make sure Apache is still in working order, you should now restart it without the PHP plug-in:
% /etc/rc.d/init.d/httpd stop
% /etc/rc.d/init.d/httpd start
With everything neat and tidy, you're ready to download and install MySQL and PHP.
Installing MySQL under Linux
MySQL is freely available for Linux from http://www.mysql (or one of its mirrors listed at http://www.mysqldownloads/mirrors.html). Download the latest stable release (listed as "recommended" on the download page). You should grab the "tarball source download" version, with filename mysql-version.tar.gz.
With the program downloaded, you should make sure you're logged in as root before proceeding with the installation, unless you only want to install MySQL in your own home directory. Begin by unpacking the downloaded file and moving into the directory that is created:
% tar xfz mysql-version.tar.gz
% cd mysql-version
Next you need to configure the MySQL install. Unless you really know what you're doing, all you should have to do is tell it where to install. I recommend /usr/local/mysql:
% ./configure --prefix=/usr/local/mysql
After sitting through the screens and screens of configuration tests, you'll eventually get back to a command prompt. You're ready to compile MySQL:
% make
After even more screens of compilation, you'll again be returned to the command prompt. You're now ready to install your newly compiled program:
% make install
MySQL is now installed, but before it can do anything useful its database files need to be installed too. Still in the directory you installed from, type the following command:
% scripts/mysql_install_db
With that done, you can delete the directory you've been working in, which just contains all the source files and temporary installation files. If you ever need to reinstall, you can just re-extract the mysql-version.tar.gz file.
With MySQL installed and ready to store information, all that's left is to get the server running on your computer. While you can run the server as the root user, or even as yourself (if, for example, you installed the server in your own home directory), the best idea is to set up a special user on the system that can do nothing but run the MySQL server. This will remove any possibility of someone using the MySQL server as a way to break into the rest of your system. To create a special MySQL user, you'll need to log in as root and type the following commands:
% /usr/sbin/groupadd mysqlgrp
% /usr/sbin/useradd -g mysqlgrp mysqlusr
By default, MySQL stores all database information in the var subdirectory of the directory to which it was installed. We want to make it so that nobody can access that directory except our new MySQL user. The following commands will do this (I'm assuming you installed MySQL to the /usr/local/mysql directory):
% cd /usr/local/mysql
% chown -R mysqlusr.mysqlgrp var
% chmod -R go-rwx var
Everything's set for you to try launching the MySQL server for the first time. From the MySQL directory, type the following command:
% bin/safe_mysqld --user=mysqlusr &
The MySQL server has now been launched by the MySQL user and will stay running (just like your Web or FTP server) until your computer is shut down. To test that the server is running properly, type the following command:
% bin/mysqladmin -u root status
A little blurb with some statistics about the MySQL server should be displayed. If you get an error message, something has gone wrong. If retracing your steps to make sure you did everything described above doesn't solve the problem, a post to the SitePoint.com Forums will probably help you pin it down in no time.
If you want to set up your MySQL server to run automatically whenever the system is running (just like your Web server probably does), you'll have to set it up to do so. In the share/mysql subdirectory of the MySQL directory, you'll find a script called mysql.server that can be added to your system startup routines to do this.
Assuming you've set up a special MySQL user to run the MySQL server, you'll need to edit the mysql.server script before you use it. Open it in your favorite text editor and change the mysql_daemon_user setting to refer to the user you created above:
mysql_daemon_user=mysqlusr
Setting up the script to be run by your system at startup is a highly operating system-dependant task. If you're not using RedHat Linux and you're not sure of how to do this, you'd be best to ask someone who knows. In RedHat Linux, the following commands (starting in the MySQL directory) will do the trick:
% cp share/mysql/mysql.server /etc/rc.d/init.d/
% cd /etc/rc.d/init.d
% chmod 500 mysql.server
% cd /etc/rc.d/rc3.d
% ln -s ../init.d/mysql.server S99mysql
% cd /etc/rc.d/rc5.d
% ln -s ../init.d/mysql.server S99mysql
That's it! To test that this works, you can reboot your system and request the status of the server as before to make sure it runs properly at startup.
Installing PHP under Linux
As mentioned above, PHP is not really a program in and of itself. Rather, it is a plug-in module for your Web server (probably Apache). There are actually three ways you can install the PHP plug-in for Apache:
• As a CGI program that Apache runs every time it needs to process a PHP-enhanced Web page.
• As an Apache module compiled right into the Apache program.
• As an Apache module loaded by Apache each time it starts up.
The first option is the easiest to install and set up, but requires Apache to launch PHP as a program on your computer every time a PHP page is requested. This can really slow down the response time of your Web server, especially if more than one request needs to be processed at a time.
The second and third options are pretty much identical in terms of performance, but since you likely already have Apache installed, you'd probably prefer to avoid downloading, recompiling, and reinstalling it from scratch. For this reason, we'll be using the third option.
Start by downloading the PHP Source package from http://www.php (or one of its mirrors listed at http://www.phpmirrors.php). At the time of this writing, PHP 4.0 was available as "Release Candidate 2"-or "almost ready but not quite". Personally I use PHP 4.0-RC2 and don't have any trouble with it. Since the final version will be out "real soon now" (likely before this series of articles is even finished), I'd recommend you install the latest version of 4.0 so you don't have to change anything when the final version is released. In case you do decide to stick with 3.0, however, I'll be sure to point out any spots in the installation procedure that would differ between the two.
The file you downloaded should be called php-version.tar.gz. We'll start by extracting the files it contains:
% tar xfz php-version.tar.gz
% cd php-version
To install PHP as a loadable Apache module, you'll need the Apache apxs program. This comes with most versions of Apache, but if you're using the copy that was installed by RedHat Linux, you'll need to install the Apache development RPM package to get it. You'll find this package on your RedHat CD or you can download it from http://www.redhat. By default, RedHat will install the program as /usr/sbin/apxs. If you see that file, you know it's installed.
For the rest of this install procedure, you'll need to be logged in as the root user, because it involves making changes to the Apache configuration files.
The next step is to configure the PHP installation program by letting it know what options you want to have enabled and where it should find the programs it needs to know about (like Apache and MySQL). Unless you know what you're doing, you should just type the command like this (all on one line):
% ./configure
--prefix=/usr/local/php
--with-config-file-path=/usr/local/php
--with-apxs=/usr/sbin/apxs
--enable-track-vars
--enable-magic-quotes
--enable-debugger
If you are installing PHP 3.0 (and not 4.0 or later), you'll also need to tell it where to find MySQL on your system with the following additional parameter:
--with-mysql=/usr/local/mysql/
After watching several screens of tests scroll by, you'll be returned to the command prompt. The following two commands will compile and then install PHP:
% make
% make install
PHP is now installed in /usr/local/php (unless you specified a different directory with the --prefix option of ./configure above), and expects to find its configuration file, named php.ini, in the same directory (unless you specified a different directory with the --with-config-file-path option of ./configure above). PHP comes with a sample php.ini file called php.ini-optimized (php.ini-dist for PHP 3.0). Copy this file from your installation work directory to where it belongs:
% cp php.ini-optimized /usr/local/php/php.ini
Or for PHP 3.0:
% cp php.ini-dist /usr/local/php/php.ini
We'll worry about fine-tuning php.ini shortly. For now, we need to make sure Apache knows where to find PHP so that it can load it when starting up. Open your Apache httpd.conf configuration file (/etc/httpd/conf/httpd.conf on RedHat Linux) in your favorite text editor. Look for a line like the following:
LoadModule php4_module lib/apache/libphp4.so
If you installed PHP 3.0, the line will read php3 instead of php4. You're looking for a new, uncommented line (no # at the start of the line), not the old line that we commented out earlier. Chances are it will not appear along with the other LoadModule lines in the file. Once you find it, you need to change the path so that it matches all the other LoadModule lines in the file. Under RedHat Linux, this means changing the line so that it looks like this:
LoadModule php4_module modules/libphp4.so
Next, look for the line starting with DirectoryIndex. This line tells Apache what filenames to use when looking for the default page for a given directory. You'll see the usual index.html and so forth, but you need to add index.php and index.php3 to that list:
DirectoryIndex index.html index.cgi ... index.php index.php3
Finally, go right to the bottom of the file and add the following line to tell Apache what file extensions should be seen as PHP files:
AddType application/x-httpd-php .phtml .php .php3
That should do it! Save your changes and restart your Apache server. All things going to plan, Apache should start up without any error messages. If you run into any trouble, the helpful folks in the SitePoint.com Forums (myself included) will be happy to help.
Post-Installation Setup Tasks
Once PHP is installed and the MySQL server is running, whether you're running under Windows or Linux or some other operating system, the very first thing to be done is to assign a "root password" for MySQL. MySQL only lets authorized users view and manipulate the information stored in its databases, and it's up to you to make sure that MySQL knows who is an authorized user and who isn't. When MySQL is first installed, it is configured with a user named "root" that has access to do pretty much anything without even entering a password. Your first task should be to assign a password to the root user so that not just anyone can go messing around in your databases.
It's important to realize that MySQL, just like a Web server or an FTP server, can be accessed from any computer on the same network. If you're working on a computer connected to the Internet, that means that anyone in the world could try to connect to your MySQL server! The need to pick a hard-to-guess password should be immediately obvious!
To set a root password for MySQL, type the following command in the bin directory of your MySQL installation (include the quotes):
mysqladmin -u root password "your new password"
To make sure MySQL has registered this change, you should tell it to reload its list of authorized users and passwords:
mysqladmin -u root reload
If this command gives you an error message telling you that access was denied, don't worry. It just means the password has already taken effect.
To try out your new password, you can request that the MySQL server tell you about its current status:
mysqladmin -u root -p status
Enter your password when prompted. You should see a brief message showing some information about the server and its current status. The -u root argument tells the program that you want to be identified as the MySQL user called "root". The -p argument tells the program to prompt you for your password before trying to connect. The status argument just tells it that you're interested in viewing the system status.
If at any time you want to shut down the MySQL server, you can use the following command. Notice the same -u root and -p arguments as before:
mysqladmin -u root -p shutdown
With your MySQL database system safe from intrusion, all that's left is to configure PHP. PHP is configured using a text file called php.ini. If you installed PHP under Windows you should already have copied php.ini into your Windows directory. If you installed PHP under Linux using the instructions above, you should already have copied php.ini into the PHP installation folder (/usr/local/php).
Open php.ini in your favorite text editor and have a glance through it. Most of the settings are pretty well explained, and most of the default settings are just fine for our purposes. Just check to make sure that your settings match with the following:
magic_quotes_gpc = On
doc_root = <the document root folder of your Web server>
extension_dir = <the PHP install directory>
If you're running PHP version 4.0, you'll also need to check the following line:
register_globals = On
And if you're running PHP version 3.0 under Windows, uncomment the following line by removing the semicolon at the start of it (PHP 4.0 doesn't need this):
extension=php_mysql.dll
Save the changes to php.ini, then restart your Web server. Under Linux, you can restart Apache if you're logged in as root by typing:
/etc/rc.d/init.d/httpd restart
You're done! Now all that's left is to test to make sure everything's working okay (see Your First PHP Script).
If Your Web Host Provides PHP and MySQL
If the host providing you with Web space has already installed and set up MySQL and PHP for you and you're just hoping to learn how to use them, there really isn't a lot you need to do. Now would be a good time to get in touch with your host and request any information you may need to access these services.
Specifically, you'll need a username and password to access the MySQL server they have set up for you. They'll probably have set up an empty database for you to use as well (this prevents you from messing with the databases of other users that share the same MySQL server), and you'll want to know its name.
There are two ways you can access the MySQL server. The first is to use telnet to log into the host and use the MySQL client programs (mysql, mysqladmin, mysqldump, etc.) installed there to interact with the MySQL server directly. The second is to install those client programs on your own computer and have them connect to the MySQL server. Your Web host may support one or both of these methods, so you'll need to ask which.
If they support logging in by telnet to do your work, you'll need a username and password for the telnet login in addition to those you'll use to access the MySQL server (they can be different). Be sure to ask for both sets of information.
If they support remote access to the MySQL server, you'll want to download a program for connecting to and interacting with the server. This article series will assume you've downloaded the set of MySQL client programs from http://www.mysql. Packages are available for Windows or Unix, and are free. Install instructions are fairly simple and are included with the packages. If you prefer something more graphical, you can download something like MySQLWinAdmin for Windows (also available from http://www.mysql). I'd really recommend getting comfortable with the basic client programs first, though, since the commands you use with them will be similar to those you include in your PHP scripts to access MySQL databases.
Your First PHP Script
It would be unfair of me to help you get everything installed and not even give you a taste of what a PHP-driven Web page looks like until next week, so here's a little something to whet your appetite.
Open up your favorite text or HTML editor and create a new file called today.php. Type the following into the file:
<HTML>
<HEAD>
<TITLE>Today's Date</TITLE>
</HEAD>
<BODY>
<P>Today's Date (according to this Web server) is
<?php
echo( date("l, F dS Y.") );
?>
</BODY>
</HTML>
Save it and place it on your Web site as you would any regular HTML file, then see what it looks like when you view it in your browser. If you haven't yet had time to set up PHP on your Web server, click here to see the results on our server.
Pretty neat, huh? If you use the view source feature in your browser, all you'll see is a regular HTML file with the date in it. The PHP code (everything between <?php and ?> in the code above) has been interpreted by the Web server and converted to normal text before sending it to your browser. The beauty of PHP (and other server-side scripting languages) is that the Web browser doesn't have to know anything about it!
Don't worry too much about the exact code I used in this example. Before too long you'll know it like the back of your hand.
Wrap-up
All things going to plan, you should now have everything you need to get MySQL and PHP installed on your Web Server. If the little example above didn't work right (for example, if the raw PHP code appeared instead of the date), then something went wrong with the setup. Drop by the SitePoint.com Forums and we'll be glad to help you figure out the problem!
In the next section, we'll learn the basics of relational databases and get started working with MySQL. If you've never even touched a database before, I promise you it'll be a real eye opener! Meanwhile, I'd love to hear what you thought of the first installment in this series of articles. Drop me a line at kevin[at]sitepoint.com, or stop by the SitePoint.com Forums to speak your mind.
Part 2: Getting Started with MySQL
Hi there, and welcome back! Last week, we went through the process of installing and setting up two software programs: PHP and MySQL. This week, we'll be concentrating on the latter by learning how to work with MySQL databases using Structured Query Language (SQL).
An Introduction to Databases
As I explained briefly last week, PHP is a server-side scripting language that lets you insert instructions into your Web pages that your Web server software (be it Apache, Personal Web Server, or whatever) will execute before sending those pages to a browser that requests them. In a brief example, I showed how it was possible to insert the current date into a Web page every time it was requested.
Now that’s all well and good, but things really get interesting when a database is added to the mix. A database server (in our case, MySQL) is a program that can store large amounts of information in an organized format that is easily accessible from scripting languages like PHP. For example, you could tell PHP to look in the database for a list of jokes that you’d like to appear on your Web site.
In this example, the jokes would be stored entirely in the database. The advantage of this would be twofold. First, instead of having to write an HTML file for each of your jokes, you could write a single PHP file designed to fetch any joke out of the database and display it. Second, to add a joke to your Web site would just be a matter of adding the joke to the database. The PHP code would take care of the rest by automatically displaying the new joke along with the rest when it fetched the list of jokes from the database.
Let’s run with this example as we look at how data is stored in a database. A database is composed of one or more 'tables', each of which contains a list of 'things'. For our joke database, we would probably start with a table called "jokes" which would contain a list of jokes. Each table in a database has one or more columns, or fields. Each column holds a certain piece of information about each "thing" in the database. Returning to our example, our "jokes" table might have columns for the text of the jokes and the dates the jokes were added to the database. Each joke that we stored in this table would then be said to be a 'row' in the table. To see where all this terminology comes from, have a look at what this table actually looks like: