O'Reilly logo

PHP in a Nutshell by Paul Hudson

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

Chapter 14. Databases

This chapter covers how to interact with your database manager using PHP, and how to format that data for output. The database systems used are MySQL 4, PEAR::DB, and SQLite.

Using MySQL with PHP

Working with MySQL through PHP is easy, as long as you have a working knowledge of SQL. This book does not attempt to teach SQL; if you are new to it, you should stop reading now, purchase a book on SQL, and then return after having read it.

Connecting to a MySQL Database

The mysql_connect() and mysql_select_db() functions connect to a database, then select a working database for use in the connection. The former usually takes three arguments, which are the IP address of a MySQL server to connect to, the username you wish to log on as, and the password for that username, like this:

    mysql_connect("db.hudzilla.org", "username", "password");

Future examples in this book will always use the username "phpuser" and the password "alm65z"; choose something more secure in your own scripts.

By default, the MySQL queries you run in PHP will be executed on the most recent connection you open in your script. Each script needs to open its own database connection through which to execute its database queries; although, by using a persistent connection, they can be made to share connections. This is discussed later in this chapter.

The first parameter in mysql_connect() can either be an IP address or a hostname. Most operating systems also allow you to use "localhost" as the local computer ...

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