Chapter 8. Connecting to a MySQL Database

In This Chapter

  • Building the connection string

  • Sending queries to a database

  • Retrieving data results

  • Formatting data output

  • Allowing user queries

  • Cleaning user-submitted data requests

Data has become the prominent feature of the Web. As you build more sophisticated sites using XHTML and CSS, you will eventually feel the need to incorporate data into your Web sites. You can do a certain amount of data work with the basic data structures built into PHP. Increasingly, Web sites turn to relational database management systems (RDBMSs) to handle their data needs. The RDBMS is a special program which accepts requests, processes data, and returns results.


This chapter assumes you already have a database available, and you have some basic knowledge of how SQL (the language of databases) works. If you are unfamiliar with these topics, please look over Book VI, which describes using data in detail.

Retrieving Data from a Database

PHP programmers frequently use MySQL as their preferred data back end. There are a number of good reasons for this:

  • MySQL is open source and free. Like PHP, MySQL is open source, so PHP and MySQL can be used together (with Apache) to build a very powerful low-cost data solution.

  • MySQL is very powerful. MySQL's capability as a data program has improved steadily, and it is now nearly as capable as commercial tools costing thousands of dollars. (And it is better than many that cost hundreds of dollars.)

  • PHP has built-in support for MySQL ...

Get HTML, XHTML, and CSS All-In-One Desk Reference For Dummies® now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.