使用 XAMPP 连接到数据库
Connection to database using XAMPP
这是我第一次使用 PHP。我在 mac.
上使用 XAMPP
MySQL、Apache 和 localhost:8080 现在都在工作。
我创建了这个名为 test.php 的文件并将其保存在 lampp/htdocs:
中
<!DOCTYPE html>
<html lang="en">
<head>
<title>Connection</title>
</head>
<body>
<?php
$servername = "localhost:8080";
$username = "root";
$password = "root";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error($conn));
}
else
{
echo "Connected successfully";
}
?>
</body>
</html>
但是,当我转到 localhose:8080/test.php 时,会打开一个空白页面,但什么也没有显示
mysqli_connect
的服务器名参数只是 服务器名。
如果您想提供一个端口号,那么它会进入 mysqli_connect
的 第五个 参数。它没有混入第一个。
也就是说:
- 由于
localhose:8080/test.php
显示的是网页,很明显您是 运行 端口 8080 上的 HTTP 服务器,而不是数据库服务器。
- 出于性能原因,您应该更喜欢使用到 MySQL/MariaDB 的套接字连接,而不是 TCP/IP 端口
端口 8080 用于您的网络服务器。您的 MySQL 服务器默认侦听端口 3306。如果端口不同,您可以检查 XAMPP 设置,但它应该是 3306。这意味着您可以省略端口号。
使用mysqli连接数据库只需要3行代码:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'user', 'pass', 'db_name', 3306); // you can omit the last argument
$mysqli->set_charset('utf8mb4'); // always set the charset
这是我第一次使用 PHP。我在 mac.
上使用 XAMPPMySQL、Apache 和 localhost:8080 现在都在工作。 我创建了这个名为 test.php 的文件并将其保存在 lampp/htdocs:
中<!DOCTYPE html>
<html lang="en">
<head>
<title>Connection</title>
</head>
<body>
<?php
$servername = "localhost:8080";
$username = "root";
$password = "root";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error($conn));
}
else
{
echo "Connected successfully";
}
?>
</body>
</html>
但是,当我转到 localhose:8080/test.php 时,会打开一个空白页面,但什么也没有显示
mysqli_connect
的服务器名参数只是 服务器名。
如果您想提供一个端口号,那么它会进入 mysqli_connect
的 第五个 参数。它没有混入第一个。
也就是说:
- 由于
localhose:8080/test.php
显示的是网页,很明显您是 运行 端口 8080 上的 HTTP 服务器,而不是数据库服务器。 - 出于性能原因,您应该更喜欢使用到 MySQL/MariaDB 的套接字连接,而不是 TCP/IP 端口
端口 8080 用于您的网络服务器。您的 MySQL 服务器默认侦听端口 3306。如果端口不同,您可以检查 XAMPP 设置,但它应该是 3306。这意味着您可以省略端口号。
使用mysqli连接数据库只需要3行代码:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'user', 'pass', 'db_name', 3306); // you can omit the last argument
$mysqli->set_charset('utf8mb4'); // always set the charset