gpt4 book ai didi

PHP和数据库连接错误

转载 作者:行者123 更新时间:2023-11-29 10:51:47 24 4
gpt4 key购买 nike

我是 PHP 和 Mysql 数据库的新手。

我正在使用 MAMP 的 phpmyadmin 来创建数据库。

通过下面的代码可以正常工作并与服务器建立连接:

<?php
include "config.php";

$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

if (mysqli_connect_error()) {
die('Connect Error ('.mysqli_connect_errno().') '.mysqli_connect_error());
}

echo 'Connected successfully.';


?>

但是,当我使用构造函数和类时,我遇到连接问题:

配置.php:

<?php
define("DB_HOST", "localhost");
define("DB_USERNAME", "root");
define("DB_PASSWORD", "root");
define("DB_DATABASE", "scapik_users");
define("DB_PORT","8889");
?>

DbConnect.php

<?php
include "config.php";

class DbConnect{

private $connect;

public function __construct(){

$this->connect = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

if (mysqli_connect_error()) {
die('Connect Error ('.mysqli_connect_errno().') '.mysqli_connect_error());
}

}

public function getDb(){
return $this->connect;
}
}
?>

有人可以帮我纠正代码吗,我猜我哪里出了问题。

谢谢。

最佳答案

创建类的对象

$obj = new DbConnect();

然后运行你的代码

<?php 
include "config.php";


class DbConnect{

private $connect;

public function __construct(){

$this->connect = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

if (mysqli_connect_error()) {
die('Connect Error ('.mysqli_connect_errno().') '.mysqli_connect_error());
} else {
echo "connection successfull";
}

}

public function getDb(){
return $this->connect;
}
}
$obj = new DbConnect();

?>

也许它会对你有所帮助。

关于PHP和数据库连接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43603824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com