【问题标题】:Connecting to Database inside Class and method nothing happens?在类和方法中连接到数据库没有任何反应?
【发布时间】:2023-01-12 17:48:37
【问题描述】:

我正在尝试将我用来连接到我的数据库的代码添加到一个类和方法中。当不在课堂内时,它回显连接成功。但是使用新代码我什么也得不到。没有错误或成功?我什至应该把它放在一个类中并使用一个方法吗?

<?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();

        }
        
    }
}


    
?>

如您所见,我尝试了一些被注释掉的东西。这些都没有帮助。

【问题讨论】:

  • 你在哪里实例化类并调用函数?你还没有向我们展示那部分

标签: php database class methods connection


【解决方案1】:

下面的代码中添加了一些更改。它工作正常

   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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    • 2019-10-12
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多