Search code examples
mysqlmamp

PHP/MySQL – Error when connecting to server


I'm using Mac OSX and I have MAMP installed, which is running my localhost server. However, there are some issues running the PHP code because the website keeps returning that there is an error when connecting to the server. I don't know what's wrong with this; maybe someone can help me out here.

PHP code:

<?php

$connection = mysql_connect("localhost", "user", "password") or die ("There was an error when connecting to the server");
mysql_select_db("topaz", $connection) or die ("There was an error when connecting to the database");

echo "

  <body style='font-family: Helvetica Neue, Helvetica, Arial, sans-serif;'>

    <div style='width: 80%; padding: 10px; border: 1px solid #000000; background-color: #ffffff;'>
      <h1>Login</h1>
    </div>

  </body>
";

?>

PHPMyAdmin Settings: enter image description here

MAMP Port Settings: enter image description here

Error: enter image description here


Solution

  • You need to establish the connection over the port specified in your control panel - by default, mysql_connect() will attempt to connect to your MySQL host over port 3306.

    Specify which port to use in the first parameter (host) of mysql_connect:

    $connection = mysql_connect("localhost:8889", "user", "password") or die ("There was an error when connecting to the server");
    //                               Here ^^^^^
    

    Mandatory note: Don't use mysql_* functions as they're deprecated. Use PDO or mysqli_* instead.