我正在尝试使用PHP连接到MySQL,但我不断收到以下错误:“ mysqli :: __ construct():(HY000 / 2002):/ Users / markjonathas / Documents / bar / database_connection中没有此类文件或目录第9行上的.php”,我已经下载了MAMP,并且正在使用PHP 7.3.1和MySQL版本8.0.16。
我曾尝试下载Sequel Pro,但是当我尝试连接数据库时,出现以下错误:“ MySQL说:无法加载身份验证插件'caching_sha2_password':dlopen(/ usr / local / lib / plugin / caching_sha2_password.so,2):找不到图片”
//code for database_connection.php:
<?php
$servername = "127.0.0.1:3306";
$username = "root";
$password = "-------";
$database = "barDB";
function db_connect() {
$connection = new mysqli($servername, $username, $password,
$database);
return $connection;
}
function db_disconenct() {
if(isset($connection)) {
$connection->close();
}
}
?>
//code for connecting to database_connection.php:
<?php
require_once("database_connection.php");
$db = db_connect();
?>
答案 0 :(得分:0)
要访问全局变量,必须将它们声明为全局变量:
function db_connect() {
global $connection, $servername, $username, $password, $database; // <<<<<<<<
$connection = new mysqli($servername, $username, $password, $database);
return $connection;
}
function db_disconenct() {
global $connection; // <<<<<
if(isset($connection)) {
$connection->close();
}
}
有关详细信息,请阅读PHP文档。
答案 1 :(得分:0)
创建一个文件,并将其命名为init.php或任何您想要的名称。
<?php
$db_name = "barDB";
$mysql_user = "root";
$mysql_pass = "-------";
$server_name = "127.0.0.1:3306";
$con = mysqli_connect($server_name, $mysql_user, $mysql_pass, $db_name);
if(!$con){
echo "Server Error";
}else{
}
?>