我想插入數據到我有一個名爲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
類訪問數據庫句柄:
「但我無法訪問$ dbc變量..」。事實上,資源變量名爲$ dbc ** 1 **($ dbc1 = mysqli_connect($ db_hostname,$ db_username,$ db_password,$ db_name);)。 – hherger
在您的插入功能中添加'global $ dbc1' –
請避免使用全局變量,這與良好做法完全相反。 – maxhb