Connect to MySQL using PHP on Ubuntu 14
<p>I am trying to connect to a MySQL database using PHP using the following code:</p>

<pre><code>&lt;?php
$servername = "localhost";
$username = "root";
$password = "pass";

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

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

<p>When using localhost, I get a message</p>

<pre><code>Connection failed: No such file or directory
</code></pre>

<p>When using 127.0.0.1 for the host, I get</p>

<pre><code>Connection failed: Connection refused
</code></pre>

<p>I have confirmed that I can connect using the command line, and the output is below</p>

<pre><code>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)
</code></pre>

<p>Connecting using TCP</p>

<pre><code>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)
</code></pre>

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

<pre><code>mysqli.default_port = 3306
mysqli.default_socket = /var/run/mysqld/mysqld.sock
mysqli.default_host = 127.0.0.1
</code></pre>

<p>And the settings from /etc/mysql/my.cnf</p>

<pre><code>[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
</code></pre>

<p>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?</p>

<p>Edit: I installed phpmyadmin and it connects to MySQL with the same settings.</p>