PHP/MySQL – 连接服务器时出错

PHP/MySQL – Error when connecting to server

我正在使用 Mac OSX 并且安装了 MAMP,这是 运行 我的本地主机服务器。但是,运行 PHP 代码存在一些问题,因为网站不断返回连接服务器时出错。我不知道这有什么问题;也许有人可以在这里帮助我。

PHP代码:

<?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>
";

?>

PHP我的管理员设置:

MAMP 端口设置:

错误:

您需要通过控制面板中指定的端口建立连接 - 默认情况下,mysql_connect() 将尝试通过端口 3306 连接到您的 MySQL 主机。

mysql_connect的第一个参数(主机)中指定要使用的端口:

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

强制性说明:不要使用 mysql_* 函数,因为它们已被弃用。请改用 PDO 或 mysqli_*。

<?php
/*
link.php
Created By Nicholas English
*/
$link = null;
$connection = null;
$servername = "";
$username = "";
$dbname = "";
$pass = "";
$mysqli = null;
$pdo = null;
$obj = null;
$pr = null;
$type = 3;
if ($type === 1) {
$mysqli = true;
$pdo = false;
$obj = true;
$pr = false;
} else {
if ($type === 2) {
$mysqli = true;
$pdo = false;
$obj = false;
$pr = true;
} else {
if ($type === 3) {
$mysqli = false;
$pdo = true;
$obj = false;
$pr = false;
} else {
$mysqli = null;
$pdo = null;
$obj = null;
$pr = null;
}
}
}
if ($mysqli === true && $obj === true) {
$link = new mysqli($servername, $username, $pass, $dbname);
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
$connection = true;
} else {
if ($mysqli === true && $pr === true) {
$link = mysqli_connect($servername, $username, $pass, $dbname);
if (!$link) {
die("Connection failed: " . mysqli_connect_error());
}
$connection = true;
} else {
if ($pdo === true && $mysqli === false) {
try {
$link = new PDO("mysql:host=$servername;dbname=$dbname", $username, $pass);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connection = true;
}
catch(PDOException $e)
{
$connection = null;
echo "Connection failed: " . $e->getMessage();
}
} else {
$link = null;
$connection = null;
}
}
}
if ($connection == null && $link == null) {
$error = 1;
}
?>