O'Reilly logo

Learning PHP and MySQL by Jon A. Phillips, Michele E. Davis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Querying the Database with PHP Functions

In this section, we introduce how to connect to a MySQL database with PHP. It's quite simple, and we'll begin shortly with examples, but we should talk briefly about what actually happens. When you try connecting to a MySQL database, the MySQL server authenticates you based on your username and password. PHP handles connecting to the database for you and allows you to immediately start performing queries and gathering data.

As in Chapter 8, we'll need the same pieces of information to connect to the database:

  • The IP address of the database server

  • The name of the database

  • The username

  • The password

If you're not sure what to use for these values, consult Chapter 7. And, before moving on, make sure you can log into your database using the mysql command-line client.

Figure 9-1 shows how the steps of the database interaction relate to the two types of resources. Building the SELECT statement happens before the third function call but is not shown. It's done with plain PHP code, not a MySQL-specific PHP function.

The interaction between functions and resources when using the database

Figure 9-1. The interaction between functions and resources when using the database

Including Database Login Details

You're going to create a file to hold the information for logging into MySQL. Storing this information in a file you include is recommended. If you change the database password, there is only one place that you need to change it regardless ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required