Search code examples
phpphpmyadminmamp

PHP MySQL_connect not working with MAMP


I have installed Mamp and PHPMyAdmin and have created a database(test_db), However the following code does not seem to connect to the server.

<?php 
//Sets database connection info
$hostname = "localhost:8888";
$username="root";
$password="root";
$db="test_db";

//starts MySQL connection
mysql_connect($hostname, $username, $password)
    or die("MySQL Connection failure.");
mysql_select_db($db)
        or die("Database could not be found");
 ?>

I have tried to both use "localhost" and "localhost:8888" for the hostname and "root" and "" as the password.

I am relatively new to this and am trying to self teach myself but I do not see what I am doing wrong.


Solution

  • Firstly, Please don't use mysql_connect since it's deprecated and use mysqli_connect instead.
    You problem was just that you didn't add database_name.

    a working example

    $hostname = "localhost:8888";
    $username="root";
    $password="root";
    $db="test_db";
    $conn = mysqli_connect(
        $hostname,
        $username,
        $password,
        $db
    ) or die('Error connecting to databse');
    

    Take a look at php.com for more information about mysqli

    Edit: Also, consider using PDO, as it's really easy.