gpt4 book ai didi

php - 无法包含 dbconenct.php

转载 作者:行者123 更新时间:2023-11-29 11:37:49 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com