如何在不将 user/pass 放入主页的情况下连接 MySQL 服务器
How to connect MySQL server without putting user/pass in the main page
我的网站上有一个主页,我正在尝试连接到 MySQL 服务器并从数据库中获取一些数据。
但问题是,当我想建立连接时,我必须将用户名和密码放在页面中,这对我来说似乎不明智。
我添加了与此问题相关的部分代码。
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
$host = "localhost";
$userName = "username";
$password = "12345678";
$dbName = "MyDB";
$connection = new mysqli($host , $userName , $password , $dbName);
if ($connection->connect_error) {
die("Connection failed due to this error : " . $connection->connect_error . '<br>');
}
else{
echo "Connected successfully";
{
</body>
</html>
将您的连接代码放入另一个文件中,例如 connection.php,在您要连接的每个页面中,您应该 require_once“connection.php”,您也可以使用该文件中的变量如果你连接它,你也可以使用 just require 而不是 require_once,但是看看它们之间的互联网差异
通常的做法是将 mysql 数据放在单独的 php 文件中。例如:
dbmain.php
<?php
$host = "localhost";
$userName = "username";
$password = "12345678";
$dbName = "MyDB";
$connection = new mysqli($host , $userName , $password , $dbName);
?>
然后您可以将此文件包含在所有 php 个需要数据库连接的文件中。
<?php include_once("dbmain.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
/// php commands, such as
//if ($result = $mysqli -> query("SELECT * FROM dbtable1")) {
// echo "Returned rows are: " . $result -> num_rows;
// Free result set
// $result -> free_result();
//}
//$mysqli -> close();
?>
</body>
</html>
我的网站上有一个主页,我正在尝试连接到 MySQL 服务器并从数据库中获取一些数据。 但问题是,当我想建立连接时,我必须将用户名和密码放在页面中,这对我来说似乎不明智。
我添加了与此问题相关的部分代码。
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
$host = "localhost";
$userName = "username";
$password = "12345678";
$dbName = "MyDB";
$connection = new mysqli($host , $userName , $password , $dbName);
if ($connection->connect_error) {
die("Connection failed due to this error : " . $connection->connect_error . '<br>');
}
else{
echo "Connected successfully";
{
</body>
</html>
将您的连接代码放入另一个文件中,例如 connection.php,在您要连接的每个页面中,您应该 require_once“connection.php”,您也可以使用该文件中的变量如果你连接它,你也可以使用 just require 而不是 require_once,但是看看它们之间的互联网差异
通常的做法是将 mysql 数据放在单独的 php 文件中。例如:
dbmain.php
<?php
$host = "localhost";
$userName = "username";
$password = "12345678";
$dbName = "MyDB";
$connection = new mysqli($host , $userName , $password , $dbName);
?>
然后您可以将此文件包含在所有 php 个需要数据库连接的文件中。
<?php include_once("dbmain.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
/// php commands, such as
//if ($result = $mysqli -> query("SELECT * FROM dbtable1")) {
// echo "Returned rows are: " . $result -> num_rows;
// Free result set
// $result -> free_result();
//}
//$mysqli -> close();
?>
</body>
</html>