如何在php中的另一个类中导入数据库连接类

时间:2014-05-19 06:24:18

标签: php oop

我将在Controller类中导入DatabaseConnector类。 DatabaseConnector类包含数据库连接查询。这两个类都是不同的php文件。

这是我的代码。

DatabaseConnector:

class DatabaseConnector
{
    public $con;
    //function for getting connected to database
    public function getConnection()
    {
        $con=mysqli_connect("localhost","root","","abcd");
        // Check connection
        if (mysqli_connect_errno()) {
          echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
        return $con;
    }
    public function closeConnection()
    {
        mysqli_close($con);
    }
}

控制器:

include "database_connector.php";
    $dc = new DatabaseConnector();
    $con = $dc->getConnection();
class Controller
{

    public function __construct(){

    }

    public function insertData()
    {

        $name = "Abcde";
        $sql = "insert into user_details values('".$name."')";
        mysql_query($con, $sql);
    }


}

我在这段代码中错了。它显示我在mysql_query($ con,$ sql)上的错误:未定义变量中的$ con; 和mysql_query()需要两个参数

请帮帮我。

1 个答案:

答案 0 :(得分:1)

您的$con不在课堂上。

include "database_connector.php";
class Controller
{
    protected $con;

    public function __construct(){
        $dc = new DatabaseConnector();
        $this->con = $dc->getConnection();
    }

    public function insertData()
    {
        $name = "Abcde";
        $sql = "insert into user_details values('".$name."')";
        mysqli_query($this->con, $sql);
    }
}

我不测试代码,但这应该可行。