2

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.

Hunter
  • 110
  • 1
  • 9
  • Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Mar 30 '16 at 21:09
  • That was not only very simple, but also the answer to my last 30 minutes of frustration. Thank you! – Hunter Mar 30 '16 at 21:12

1 Answers1

2

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.

Slavi
  • 576
  • 1
  • 3
  • 18