Connecting PHP to MySQL in MAMP

I had some struggle in connecting MAMP to MySQL, but finally I found a code that works just fine.

It doesn't validate fields and values (I let that to you), and it adds only a small amount data (username and password). However the difficult part is the connection to the database and insertion of values into tables. Expanding the code to a wider range of needs should be trivial. Use it as a template.

Here's the code.

/**
  * Shortcut to username and password
*/
$username = $_POST['username'];
$password = $_POST['password'];

/**
  * Connect to the database
  * http://php.net/manual/en/mysqli.real-connect.php
*/
$user = 'root';
$pass = 'root';
$db   = 'loginapp';
$host = 'localhost';
$port = 3306;
$link = mysqli_init();
if (!$link) {
    die('mysqli_init failed');
}

if (!$link->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
    die('Setting MYSQLI_INIT_COMMAND failed');
}

if (!$link->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
    die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}

if (!$link->real_connect(
  $host,
  $user,
  $pass,
  $db
)) {
    die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}

// Quick test
// echo 'Success... ' . $link->host_info . "\n";

$connection = $link->real_connect(
  $host,
  $user,
  $pass,
  $db
);

/**
  * More testing
*/
// echo '$link: '; print_r($link); echo "\n";
// echo '$connection: '; print($connection); echo "\n";
// echo '$connection _r: '; print_r($connection); echo "\n";

if (!$connection) {
  die('Database connection failed.');
}

/**
  * Insert data into table
*/
$query  = "INSERT INTO users(username, password)";
$query .= "VALUES ('$username', '$password')";

// $result = mysqli_query($connection, $query);
$result = mysqli_query($link, $query);

if (!$result) {
  die('Error: ' . mysqli_error($link));
}

/**
  * Close connection
*/
$link->close();