2016-02-18 51 views
1

我想插入數據到我有一個名爲InsertTodb的類的數據庫。但是我無法通過類訪問$ dbc變量(在dbconfig .php中)。下面是代碼通過類訪問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的新手。請幫助解決它。通過$this->dbc,例如

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

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

    // ... 
} 

裏面的你InsertTodb類訪問數據庫句柄:

+0

「但我無法訪問$ dbc變量..」。事實上,資源變量名爲$ dbc ** 1 **($ dbc1 = mysqli_connect($ db_hostname,$ db_username,$ db_password,$ db_name);)。 – hherger

+0

在您的插入功能中添加'global $ dbc1' –

+0

請避免使用全局變量,這與良好做法完全相反。 – maxhb

回答

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 $值等(你應該讓它們在所有一次作爲數組或對象),但現在應該足夠了。

+0

謝謝謝爾蓋,現在工作正常。是的,我會用數組來完成它。我正在逐漸走下去。我想檢查這個基本代碼是否工作。 – Rajesh

3

你可以數據庫句柄添加到您類的構造函數這樣mysqli_query($this->dbc, $insquery)

在你的代碼必須通過$dbc1到新創建的對象:

$ins = new InsertTodb($dbc1);