我正在使用php处理基本的用户操作系统,但是我无法链接dbconnect并从中获取连接变量。
这是我的代码:
dbconnect.php
<?php
$con = mysqli_connect("localhost","root","","realestatecompany");
if(!$con) {
echo "Error";
}
//$con->close();
?>
objects.php
<?php
require_once 'dbconnector.php';
class userAccount {
public $userName;
public $userPass;
public $userType;
public function __construct ($UserName, $Password, $Type, $con) {
$this->userName = $UserName;
$this->userPass = $Password;
$this->userType = $Type;
}
public function writeInDB() {
$sql = "INSERT INTO login (userName,userPass,userType) values (".$this->userName.",".$this->userPass.",".$this->userType.")";
if ($con->query($sql) === TRUE) {
echo "Record Added successfully";
} else {
echo "Error Adding record: " . $conn->error;
}
}
public function editInDB($userNewAccount, $userID) {
$a = $userNewAccount->userName;
$b = $userNewAccount->userPass;
$c = $userNewAccount->userType;
$sql = "UPDATE login SET userName =".$a.", userPass ='".$b."', userType =".$c." WHERE userID =".$userID;
echo $sql;
}
}
$x = new userAccount("Heba", "Taba3", 1, $con);
$x->writeInDB();
&GT;
输出
Notice: Undefined variable: con in D:\xampp\htdocs\swproject\objects.php on line 14
Fatal error: Uncaught Error: Call to a member function query() on unknown in D:\xampp\htdocs\swproject\objects.php:14 Stack trace: #0 D:\xampp\htdocs\swproject\objects.php(29): userAccount->writeInDB() #1 {main} thrown in D:\xampp\htdocs\swproject\objects.php on line 14
任何帮助?
答案 0 :(得分:1)
您的问题是可变范围,而且您忘记将$con
参数保存为__contruct()
作为您班级的财产,并且未将其用作您班级的属性
<?php
require_once 'dbconnector.php'; //<-- should this be 'dbconnect.php`
class userAccount {
public $userName;
public $userPass;
public $userType;
public $con;
public function __construct ($UserName, $Password, $Type, $con) {
$this->userName = $UserName;
$this->userPass = $Password;
$this->userType = $Type;
$this->con = $con;
}
public function writeInDB() {
$sql = "INSERT INTO login
(userName,userPass,userType)
values (".$this->userName.",".$this->userPass.
",".$this->userType.")";
if ($this->con->query($sql) === TRUE) {
echo "Record Added successfully";
} else {
echo "Error Adding record: " . $conn->error;
}
}
public function editInDB($userNewAccount, $userID) {
$a = $userNewAccount->userName;
$b = $userNewAccount->userPass;
$c = $userNewAccount->userType;
$sql = "UPDATE login SET userName =".$a.", userPass ='".$b."', userType =".$c." WHERE userID =".$userID;
echo $sql;
}
}
$x = new userAccount("Heba", "Taba3", 1, $con);
$x->writeInDB();