Connecting to a MySQL database

resource mysqli_connect ( [string server [, string username [, string password [, string database_name [, int port_number [, string socket]]]]]])

To connect to MySQL, you need the mysqli_connect() function. This usually takes four arguments: the IP address of a MySQL server to connect to, the username you wish to logon as, the password for that username, and the name of the database you want to use. This function opens a database connection for your PHP script, allowing you to execute commands and read results from your database. Don't worry about disconnecting from your database - PHP automatically disconnects you when it finishes running your script. Note that examples in this book will always use the username "phpuser" and the password "alm65z" - do not use them in your own scripts, for security reasons!

All SQL queries you run in PHP must be run on a specific database connection, which is why mysqli_connect() returns a database connection when it's called. You will need to store this in a variable so you can use it when you want to make queries.

The first parameter to mysqli_connect() can either by an IP address, or a hostname. Most operating systems also allow you to use "localhost" as the local computer and have MySQL connect directly through a local socket. Alternatively, you can specify 127.0.0.1, which is also the local computer, and have MySQL connect through TCP/IP, which is a fraction slower. To connect to a remote server, just enter either the hostname (e.g. www.microsoft.com) or the IP address (e.g. 212.113.192.101) as the first parameter, and your data will be transparently sent over the Internet.

Author's Note: In small scenarios, having the PHP server and MySQL server on the same machine makes the most sense, and allows for very high performance. However, in order to be more scalable you will need to have your database server separate from your PHP server, with the two connected via a high-speed network.

Here's a simple example of connecting to a database:

<?php
    $db = mysqli_connect("localhost", "phpuser", "alm65z", "phpdb");
?>

Author's Note: Once you are connected, you can use the function mysqli_ping() to check whether the server is alive. Pass it the database connection you got back from mysqli_connect() and it will return true if the server was contacted or false if the connection appears to be lost.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Querying and formatting >>

Previous chapter: Using MySQL with PHP

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.