gpt4 book ai didi

php - 无法从我的数据库类访问连接详细信息

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

嗨,我正在使用 oophp 创建注册和登录系统,我正在尝试检查数据库中是否已存在电子邮件或用户名,但是当我尝试调用数据库类时,我不断收到这些错误,任何帮助都会受到赞赏。

Notice: Undefined variable: Database in C:\Users\josh\xampp-win32-1.8.3-5-VC11\xampp\htdocs\oop_system\include\class.user.php on line 14

Notice: Trying to get property of non-object in C:\Users\josh\xampp-win32-1.8.3-5-VC11\xampp\htdocs\oop_system\include\class.user.php on line 14

Fatal error: Call to a member function query() on a non-object in C:\Users\josh\xampp-win32-1.8.3-5-VC11\xampp\htdocs\oop_system\include\class.user.php on line 14

用户类别

<?php 
include "db_config.php";

class User{

/*** for registration process ***/
public function reg_user($name,$username,$password,$email){


$password = md5($password);
$sql="SELECT * FROM users WHERE uname='$username' OR uemail='$email'";

//checking if the username or email is available in db
$check = $Database->getConnection->query($sql) ;
$count_row = $check->num_rows;

//if the username is not in db then insert to the table
if ($count_row == 0){
$sql1="INSERT INTO users SET uname='$username', upass='$password', fullname='$name', uemail='$email'";
$result = mysqli_query($this->db,$sql1) or die(mysqli_connect_errno()."Data cannot inserted");
return $result;
}
else { return false;}
}
}
?>

db_config 类

<?php
/*
* Mysql database class - only one connection alowed
*/
class Database {
private $_connection;
private static $_instance; //The single instance
private $_host = "localhost";
private $_username = "root";
private $_password = "";
private $_database = "oop";
/*
Get an instance of the Database
@return Instance
*/
public static function getInstance() {
if(!self::$_instance) { // If no instance then make one
self::$_instance = new self();
}
return self::$_instance;
}
// Constructor
private function __construct() {
$this->_connection = new mysqli($this->_host, $this->_username,
$this->_password, $this->_database);

// Error handling
if(mysqli_connect_error()) {
trigger_error("Failed to conencto to MySQL: " . mysql_connect_error(),
E_USER_ERROR);
}
}
// Magic method clone is empty to prevent duplication of connection
private function __clone() { }
// Get mysqli connection
public function getConnection() {
return $this->_connection;
}
}
?>

最佳答案

  1. Database 是一个类,而不是变量,因此您可以使用 Database 来调用它,而不是 $Database
  2. getConnection 是一个函数/方法,而不是变量/字段,因此您必须在其名称后使用括号:getConnection()
  3. getConnection 是一个非静态函数,因此您无法在 Database 上调用它,您必须获取该类的实例(使用 >数据库::getInstance())。

总而言之,替换这一行:

$check = $Database->getConnection->query($sql);

这样:

$check = Database::getInstance()->getConnection()->query($sql);

关于php - 无法从我的数据库类访问连接详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33055066/

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