在Ubuntu 14上使用PHP连接到MySQL

I am trying to connect to a MySQL database using PHP using the following code:

<?php
$servername = "localhost";
$username = "root";
$password = "pass";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
?>

When using localhost, I get a message

Connection failed: No such file or directory

When using 127.0.0.1 for the host, I get

Connection failed: Connection refused

I have confirmed that I can connect using the command line, and the output is below

mysql -u root -p pass -h localhost
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 7282
Server version: 5.5.47-0ubuntu0.14.04.1-log (Ubuntu)

Connecting using TCP

mysql -u root -p pass -h 127.0.0.1
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 7318
Server version: 5.5.47-0ubuntu0.14.04.1-log (Ubuntu)

The following is the relevant mysqli section of the php.ini file in /etc/php5/apache2

mysqli.default_port = 3306
mysqli.default_socket = /var/run/mysqld/mysqld.sock
mysqli.default_host = 127.0.0.1

And the settings from /etc/mysql/my.cnf

[mysqld]
#
# * Basic Settings
#
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
.
.
.
bind-address        = 127.0.0.1

I have tried using PDO to connect to the database with the same results. Can anyone see a configuration setting that is not correct, or have another idea of what could be wrong?

Edit: I installed phpmyadmin and it connects to MySQL with the same settings.

Try to do this?

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
?>