# Connecting to MySQL using PHP

> Connect a PHP script to a MySQL database using mysqli or PDO, with example code, plus how to connect to a remote database.

Source: https://helpcenter.ruachost.com/developers/databases/connecting-to-mysql-using-php/

**Connecting to MySQL using PHP**\
This article explains several methods for connecting to a MySQL database using PHP:

- MySQL Improved (mysqli) PHP extension
- PDO (PHP Data Objects)
- Legacy MySQL (mysql_) functions
- Connecting to remote MySQL databases using PHP

**Tip:** MySQL databases and users must already exist before using these methods.

**Method #1: Connect using MySQL Improved (mysqli)**\
The MySQL Improved extension uses the `mysqli` class, replacing the deprecated MySQL functions.

Example code to connect and select a database (replace `username`, `password`, and `dbname` with your details):

```
<?php
    $mysqli = new mysqli("localhost", "username", "password", "dbname");
?>
```

Run a SQL query on the `employees` table:

```
<?php
    $result = $mysqli->query("SELECT lastname FROM employees");
?>
```

**Method #2: Connect using PHP Data Objects (PDO)**\
PDO abstracts database access and supports multiple database types.

Example code to connect and select a database:

```
<?php
    $myPDO = new PDO('mysql:host=localhost;dbname=dbname', 'username', 'password');
?>
```

Run a SQL query:

```
<?php
    $result = $myPDO->query("SELECT lastname FROM employees");
?>
```

**Method #3: Connect using legacy PHP MySQL functions**\
Legacy `mysql_` functions are deprecated in PHP 5.5 and will be removed in future versions. Use them only for backward compatibility.

Example code to connect and select a database:

```
<?php
    mysql_connect('localhost','username','password');
    mysql_select_db("dbname");
?>
```

Run a SQL query:

```
<?php
    $result = mysql_query('SELECT lastname FROM employees');
?>
```

**Connecting to remote MySQL databases using PHP**\
To connect from a remote location, do the following:

1. Enable the IP address for remote access on the hosting server.
2. Change the PHP connection string to use the server name instead of `localhost`.

Example using `mysqli` for a remote server:

```
<?php
    $mysqli = new mysqli("localhost", "username", "password", "dbname");
?>
```

**Note:** If your IP is not added for remote access, you will get "Access denied" errors.

## More information

- [MySQL Improved (mysqli) PHP extension](http://www.php.net/manual/en/book.mysqli.php)
- [PDO (PHP Data Objects)](http://www.php.net/manual/en/book.pdo.php)
- [Legacy MySQL functions](http://www.php.net/manual/en/book.mysql.php)
