PHP / MySQL - 连接到服务器时出错

时间:2015-07-22 14:31:43

标签: mysql mamp

我正在使用Mac OSX并且我安装了MAMP,它正在运行我的localhost服务器。但是,运行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>
";

?>

PHPMyAdmin设置: enter image description here

MAMP端口设置: enter image description here

错误: enter image description here

2 个答案:

答案 0 :(得分:1)

您需要通过控制面板中指定的端口建立连接 - 默认情况下,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_ *。

答案 1 :(得分:0)

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