php 连接到类和方法内部的数据库时没有任何React?

6yoyoihd  于 2023-01-16  发布在  PHP
关注(0)|答案(1)|浏览(108)

我试图添加我的代码,我用来连接到我的数据库到一个类和方法。当不在类中,它回显连接成功。但与新的代码,我没有得到任何东西。没有错误或成功?我甚至应该把它放在一个类中,并使用一个方法?

<?php

class DBconfig
{

    private $servername = "localhost";
    private $username = "*********";
    private $password = "***************";

    // public function __construct($servername,$username,$password)
    // {

    //     $this -> servername = $servername;
    //     $this -> username = $username;
    //     $this -> password = $password;
    // }

    public function dbConnect($servername,$username,$password)
    {

            // $servername = $this -> servername;
            // $username = $this -> username;
            // $password = $this -> password;

        try 
        {

            $conn = new PDO("mysql:host=$servername; dbname = training", $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();

        }
        
    }
}

    
?>

正如你所看到的,我已经尝试了几件被注解掉的事情。这些都没有帮助。

biswetbf

biswetbf1#

对下面的代码做了一些修改,运行良好

class DBconfig
{

private $servername = "localhost";
private $db = "**************";
private $username = "**************";
private $password = "**************";

private $conn;

public function __construct()
{
    $this->dbConnect();
}

public function dbConnect()
{
    try 
    {
        $this->conn = new PDO("mysql:host=$this->servername; dbname = $this->db", $this->username, $this->password);
        $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "Connected successfully";
    } 

    catch(PDOException $e) 
    {
        echo "Connection failed: " . $e->getMessage();
    }
}

public function getConnection(){
    return $this->conn;
}
}

$db = new DBconfig();
$conn = $db->getConnection();

相关问题