PHP Connect to MySQL

This article describes several methods for connecting to a MySQL database using PHP:

  • MySQL Improved (mysqli) extension
  • PDO (PHP Data Objects)
  • Legacy MySQL (mysql_) functions
  • Connecting to a remote MySQL database using PHP
  • CONNECTING TO MYSQL USING THE MYSQL IMPROVED EXTENSION

    The MySQL Improved extension uses the mysqli class, which replaces the set of legacy MySQL functions.

    To connect to MySQL using the MySQL Improved extension, follow these steps:

    1. Use the following PHP code to connect to MySQL and select a database. Replace username with your username, password with your password, and dbname with the database name:

    Example -

    2. After the code connects to MySQL and selects the database, you can run SQL queries and perform other operations. For example, the following PHP code runs a SQL query that extracts the last names from the employees table, and stores the result in the $result variable:

    Example -

    CONNECTING TO MYSQL USING THE LEGACY MYSQL FUNCTIONS

    The original PHP MySQL functions (whose names begin with mysql_) are deprecated in PHP 5.5, and will eventually be removed from PHP. Therefore, you should only use these functions when absolutely necessary for backward compatibility. If possible, use the MySQL Improved extension or PDO instead.

    To connect to MySQL using the legacy PHP MySQL functions, follow these steps:

    1. Use the following PHP code to connect to MySQL and select a database. Replace username with your username, password with your password, and dbname with the database name:

    Example -

    2. After the code connects to MySQL and selects the database, you can run SQL queries and perform other operations. For example, the following PHP code runs a SQL query that extracts the last names from the employees table, and stores the result in the $result variable:

    Example -

    CONNECTING TO A REMOTE MYSQL DATABASE USING PHP

    The previous examples all assume that the PHP script runs on the same server where the MySQL database is located. But what if you want to use PHP to connect to a MySQL database from a remote location? For example, you may want to connect to your A2 Hosting database from a home computer or from another web server.

  • On the A2 Hosting server, enable the connecting IP address for remote access.
  • In your PHP code, change the MySQL connection string to use the A2 Hosting server name instead of localhost. For example, the following PHP code uses mysqli to connect to the A2 Hosting server a2ss25.a2hosting.com:
  • Example -