通过类访问数据库配置文件 - PHP


Accessing dbconfig file through class - 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; 
        }
}
}
?>

我的数据库配置文件

<?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,在 ..." 中给出空值。我是OOP的新手。请帮助修复它。

你可以像这样将数据库句柄添加到类的构造函数中:

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);
你应该稍微

重构一下你的代码。首先

<?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)) {
            ...
        }
        ...
    }
    ...
}

所有这些 $data 1、$data 2 等值看起来insertData()有点笨拙(您应该将它们作为数组或对象一次性传递),但现在这应该足够了。