developer.com
Search EarthWeb
CodeGuru | Gamelan | Jars | Wireless | Discussions
Navigate developer.com
Architecture & Design  
Database  
Java
Languages & Tools
Microsoft & .NET
Open Source  
Project Management  
Security  
Techniques  
Voice  
Web Services  
Wireless/Mobile
XML  
Technology Jobs  

   Developer.com Webcasts:
  The Impact of Coding Standards and Code Reviews

  Project Management for the Developer

  Defining Your Own Software Development Methodology

  more Webcasts...




See the Winners!


Developer Jobs

Be a Commerce Partner
Memory Upgrades
Data Center Solutions
GPS
Rackmount LCD Monitor
Home Improvement
Corporate Gifts
KVM Switches
Logo Design
PDA Phones & Cases
Web Design
Televisions
Domain registration
Shop
Build a Server Rack

 


Web Devs:
Moonlight as a Game Developer and Win Cool Prizes by Accepting the RIA Run Challenge

Now, your mission--should you choose to accept: Take your shot at gaming stardom if you think you might have what it takes to build a cool RIA game and you could win an Xbox 360 or other fabulous prizes. Hurry! You only have until May 15, 2008 to enter. »

 
Article:
Leveraging Your Flash Development with Silverlight

You're not giving up Flash any time soon (and we don't blame you.) But if you could get your Flash application working in Silverlight, why wouldn't you? We show you the tools and techniques required to have your rockin' Flash application rolled for Silverlight. Learn more here. »

 
Article:
What Does it Take to Build the Best RIA?

With the proliferation of Rich Interactive Application (RIA) platform choices out there, you no longer have to take a one-size-fits-all approach to developing your next RIA application. Knowing the strengths (and weaknesses) of each platform can help you to decide the best RIA for your next application. »

 
Developer News -
Sun Latest to Help App Vendors Get 'SasSy'    April 24, 2008
Ubuntu's 'Hardy' Cozy With Windows    April 24, 2008
The $4.6B Business of The Social    April 22, 2008
Office 2007 Fails The OOXML Test    April 22, 2008
Free Tech Newsletter -

Best Practices for Developing a Web Site: Checklists, Tips, Strategies & More. Download Exclusive eBook Now.

Building Database-Driven Applications with PHP and MySQL
By Elizabeth Fulghum

Go to page: 1  2  3  Next  

Almost every dynamic Web application eventually boils down to accessing, manipulating, and presenting information. A forum is an idea example of this type of application. Users register at the site; their information is added to the database. Someone wants to post a new message? The database is queried to validate the user and again to store the message once the user has finished writing it. Displaying each page, the forum listing, the threads listing, the message listing, and the user profile pages relies on accessing stored information. All apparently separate sets of information are stored together in a single database and it's all pulled together with languages such as PHP and SQL.

This article is the first of four parts, focusing on building database-driven applications with PHP and MySQL. In this part, you will be introduced to MySQL and SQL, discover what databases look like, and begin to learn the commands to work with them.

Why MySQL?

There's a plethora of database products out there, from Oracle, mSQL, and PostgreSQL to MS Access. Even amid all this competition, MySQL has managed to become and remain exceptionally popular in the *nix programming community and the first choice for PHP developers.

There are several reasons for this. The biggest draw is the fact that MySQL is completely free under the GPL license, which gives it an instant price advantage over often-expensive commercial options. It is also open source, enjoying the benefits of community development and quick attention to bugs. And because it is natively supported by PHP without compiling in any additional modules, it is a natural choice for Web hosts that want to offer database support.

These all add up to make MySQL a compelling choice.

Free and accessible do not equate a less capable product, though; for small to medium-large applications, MySQL is also fast, adaptable, and feature-rich. Performance benchmarks against other databases are frequently biased (in one direction or another), but they generally give MySQL high marks. MySQL's own documentation indicates that, barring an operating system's own limitations, databases can be as large as 8 million terabytes.

Talking to Databases Using SQL

SQL is an abbreviation for Structured Query Language. It is a surprising natural language that allows us to "talk" to relational databases, such as MySQL, to request and modify data. It also allows us to get information about and modify the framework that contains the data, databases themselves, and tables within them. The queries formed with SQL can range from the simple to the very complex, which makes it an extremely powerful tool for working with data.

SQL is not exclusive to MySQL, nor should it be mistaken as being a part of PHP. It's also not the only database query language out there. It is, however, the most popular. If you learn how to speak SQL, that knowledge translates to a range of other popular database products.

The Anatomy of a Database

Simply put, a database is a collection of structured information. Relational databases, such as MySQL, allow information to broken into sets called tables. Take a look at this simple illustration of a table with some data in it:

users
Id
name
email
1
John
john@doe.com
2
Jane
jane@doe.com
3
Jack
test@test.com

Tables are very similar to associative arrays. This table has three rows of distinct information representing different users. Rows are also known as records. It is also divided into three columns: id, name, and email. The intersection of a row and a column is considered a field (The difference between a column and a field is a technical one and the terms are frequently used interchangeably), which is populated with the actual data.

Keep the structure of this sample database in mind; we'll be returning to it later in the article to illustrate several examples.

Working with Existing Databases Through PHP

Whether you are using PHP and MySQL, or another combination, the same basic procedure for working with a database applies.

First, a connection to the database server is established. This connection usually lasts for the lifetime of the running script. Additionally, as you will later see, there are instances where they can be contiguous across scripts.

Next, a specific database is selected to work with. Only one database at a time can be selected per connection, but you can switch to different databases without terminating the connection. You can also have multiple connections established within the script, each with an independent selected database.

Finally, once you have a connection established and a database selected, you can begin to work with the tables within them by using SQL to issue various commands. Data can be retrieved, added, modified, or deleted, and changes can be made to the selected database itself.

When finished, the connection to the database server is terminated manually with mysql_close(), or automatically with the end of the script.

Let's take a closer look at each step separately.

Connecting to MySQL

Just like a multi-user computer system or an FTP server, MySQL allows different user accounts to be established with individual levels of access. To establish a connection to MySQL, three pieces of information are required: the hostname of the database server, the username for the account, and the associated password.

This information is passed to the mysql_connect() function, which attempts to establish the connection:

$connect = mysql_connect('hostname','username','password');

The function returns a value TRUE on success, and FALSE on failure, so it is useful (though not necessary) to assign the function to a variable. In the above example, $connect is used. It can be evaluated to avoid performing any additional queries if the connection attempt failed:

if ($connect==FALSE) {
print "Database connection failed";
exit;
}

It is also useful to store the results in a variable because the function returns a unique connection identifier upon success. The variable then can be passed to any of PHP's MySQL handling functions (typically as the second parameter) to specify that this database connection should be used, as opposed to any other active ones within the script.

Selecting a Database

Once a connection is set up, the next step is to select a database. To do this, all that is needed is the name of an existing database:

mysql_select_db('database');

As with mysql_connect(), this function returns TRUE or FALSE depending on whether the database was successfully selected. To specify which connection the function should use, we can pass a connection identifier to the function:

mysql_select_db('database',$connect);

Without the second parameter, the function uses the database connection that was last established within the script.

Go to page: 1  2  3  Next  


Tools:
Add www.developer.com to your favorites
Add www.developer.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed


Database Archives

Data Sheet: IBM Information Server Blade
Flash Demo: Learn how IBM Information Server Blade is easy to manage, highly scalable and efficient.
Whitepaper: Embeddable Content Platform for OEM's
Best Practices for Developing a Web Site. Checklists, Tips & Strategies. Download Exclusive eBook Now.
Whitepaper: Enterprise Information Integration--Deployment Best Practices for Low-Cost Implementation



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES