我在使用SQL时遇到了麻烦,我可以通过Mamp连接到SQL并访问Phpmyadmin,尽管当我尝试在浏览器中将带有该代码的数据库显示到我的代码编辑器中时:
<?php
$link = mysqli_connect("localhost:8000", "root", "password",
"Portfolio");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging error: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
echo "Success: A proper connection to MySQL was made! The Portfolio
database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;
mysqli_close($link);
?>
浏览器指示我在代码中编写的消息,因此在某处建立了连接: 错误:无法连接到MySQL。调试错误:2002调试错误:连接被拒绝
我每次输入的网址是:http://localhost:8888/bdd.php “ bdd.php”是我的文件名。
这让我发疯,我已经尝试了很多事情(在php init上用“ path”更改代码,重新安装了mamp,mysql ..),但仍然不知道出了什么问题,几个月前我开始编码真的需要帮助!
干杯!
答案 0 :(得分:0)
在MAMP上,MySQL的默认端口是8889,但是php期望用于mysql的端口是3306。因此,您需要打开MAMP,转到首选项,并将MAMP mysql端口更改为3306,然后重新启动mysql。服务器。现在,使用host = localhost,user = root,pass = root可以成功连接。
我建议您使用PDO防止SQL注入。
PDO示例:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
MySQLi面向对象
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
MySQLi程序
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
答案 1 :(得分:0)
提及主机名称为“ Localhost”。 $ link = mysqli_connect(“ localhost”,“ root”,“ password”,“ Portfolio”);