作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 php 开发一个基本的用户操作系统,但我无法链接 dbconnect 并从中获取连接变量。
这是我的代码:
dbconnect.php
<?php
$con = mysqli_connect("localhost","root","","realestatecompany");
if(!$con) {
echo "Error";
}
//$con->close();
?>
对象.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();
?>
输出
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
有什么帮助吗?
最佳答案
您的问题是变量作用域,而且您忘记保存传递给 __contruct()
的 $con
参数作为类的属性,并且没有使用它作为你的类(class)的属性(property)
<?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();
关于php - 无法包含 dbconenct.php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36306370/
我正在使用 php 开发一个基本的用户操作系统,但我无法链接 dbconnect 并从中获取连接变量。 这是我的代码: dbconnect.php close(); ?> 对象.php userNam
我是一名优秀的程序员,十分优秀!