通过类访问dbconfig文件 - PHP

时间:2016-02-18 07:59:09

标签: php

我想将数据插入到我有一个名为InsertTodb的类的数据库中。但我无法通过类访问$ dbc变量(在dbconfig .php中)。这是代码

我的班级档案

<?php
require("dbconfig.php");
class InsertTodb {
    public $tableNme;
    public $data1;
    public $data2;
    public $data3;
    public $arg1;
    public $arg2;
    public $arg3;


    function insertData($tableName, $data1, $data2, $data3, $val1, $val2, $val3) {
        $this->tableNme = $tableName;       
        $this->data1 = $data1;
        $this->data2 = $data2;
        $this->data3 = $data3;
        $this->arg1 = $val1;        
        $this->arg2 = $val2;        
        $this->arg3 = $val3;        

        $insquery = "insert into ".$this->tableNme."(".$this->data1.", ".$this->data2.", ".$this->data3.") values('".$this->arg1."', '".$this->arg2."',' ".$this->arg3."')";
        echo $insquery; 

        if(mysqli_query($dbc, $insquery)) {                 
        $success = "Product added successfully."; 
        echo $success; 
        }
        else {
        $failed = "Error adding product."; 
        echo $failed; 
        }
}
}
?>

我的dbconfig文件

<?php
$db_hostname = 'localhost';
$db_username = 'root';
$db_password = '';
$db_name = 'oop';

$dbc1 = mysqli_connect ($db_hostname,$db_username, $db_password,$db_name);

if (mysqli_connect_errno()) {
echo "Could not establish database connection!";
exit();
}
?>

我的代码

<?php

include "InsertTOdb.php";

$ins = new InsertTodb();

$ins->insertData("tableone", "name", "age", "desig",  "Guru", "25", "Accountant");

?>

当我运行上面的程序时,它显示错误“通知:未定义的变量:dbc”和...“警告:mysqli_query()期望参数1为mysqli,在......中给出null”。我是OOP的新手。请帮忙解决。

2 个答案:

答案 0 :(得分:3)

您可以将数据库句柄添加到您的类的构造函数中,如下所示:

class InsertTodb {
  // Define property to store $dbc
  protected $dbc;

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

  // ...
}

您的InsertTodb类内部通过$this->dbc访问数据库句柄,例如mysqli_query($this->dbc, $insquery)

在您的代码中,您必须将$dbc1传递给新创建的对象:

$ins = new InsertTodb($dbc1);

答案 1 :(得分:1)

您应该稍微重构一下代码。首先,

<?php
include "dbconfig.php"; // Add this first.
include "InsertTOdb.php";
$ins = new InsertTodb($dbc1); // Feed the connector to your class.
$ins->insertData("tableone", "name", "age", "desig",  "Guru", "25", "Accountant");
?>

现在稍微更改一下InsertTOdb类:

class InsertTodb {
    private $dbc;
    public function __construct($dbc) {
        $this->dbc = $dbc;
    }

    // ... the rest of class's properties ...
    function insertData($tableName, $data1, $data2, $data3, $val1, $val2, $val3) {
        ...
        // Change $dbc to $this->dbc.
        if(mysqli_query($this->dbc, $insquery)) {
            ...
        }
        ...
    }
    ...
}

你的insertData()看起来有点笨重,所有这些$ data1,$ data2等值(你应该将它们全部作为数组或对象传递给它们),但现在这应该足够了。