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 ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.