O'Reilly logo

Upgrading to PHP 5 by Adam Trachtenberg

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

Before and After: Connecting to the Database Server

Before you can issue queries, you need to connect to the MySQL server. This sounds so basic that you’d think it would be the same in both versions of the MySQL extension, but there are quite a few changes.

Connecting isn’t just specifying the location of your database and providing a username and password. You also specify a variety of configuration options, such as whether to use SSL and the number of seconds before the connection times out.

mysql: Making a Connection

The mysql connection functions take five parameters:

mysql_connect(server, username, password, new_link, client_flags)

All of these parameters are actually optional, because the extension defaults to values specified in a series of MySQL-related configuration directives, such as mysql.default_host.

The server parameter is usually the same as the host, but you can also append a port name or a path to a socket. For example, if your database runs on port 3307 on db.example.org:

mysql_connect('db.example.org:3307');

Separate the hostname and port with a colon (:) so PHP can tell them apart.

The username and password variables are not the username and password for your local account, but for MySQL’s account system.

By default, if you try to reconnect to the same database with the same set of credentials, PHP will reuse the existing connection. Setting new_link to true forces PHP to always make another link to MySQL.

Use the final parameter, client_flags, to control the session. ...

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