我写脚本登录php oop。 我创建了文件Db.php方法runQuery:
function runQuery($query) {
$this->last_query_result = $this->conn->query($query);
if (!$this->last_query_result) {
$this->setError("Nie udalo sie wykonac zapytania: " . $this->conn->error);
}
}
在文件login.php中我创建了新方法loginUser:
public function loginUser($login, $pass) {
$this->result = parent::runQuery("SELECT * FROM users WHERE name = '" . $login . "' AND pass='" . $pass . "'");
var_dump($this->result);
}
问题是查询返回NULL。
整个文件db.php
class DbUser {
private $conn;
private $host;
private $user;
private $pass;
private $base;
private $last_query_result;
function __construct($host, $user, $pass, $base) {
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->base = $base;
$this->connect();
}
public function setError($error) {
throw new Exception($error);
}
protected function connect() {
$this->conn = @new mysqli($this->host, $this->user, $this->pass, $this->base);
if ($this->conn->connect_errno) {
$this->setError("Nie udalo sie polaczyc z baza danych: " . $this->conn->connect_error);
}
}
function runQuery($query) {
$this->last_query_result = $this->conn->query($query);
if (!$this->last_query_result) {
$this->setError("Nie udalo sie wykonac zapytania: " . $this->conn->error);
}
}
function fullList() {
$return = array();
while (($row = mysqli_fetch_assoc($this->last_query_result)) !== NULL) {
$return[] = $row;
}
return $return;
}
}
并提交login.php文件
//kalsa logowania uzytkownika
include 'db.php';
class login extends DbUser {
private $login;
private $pass;
private $result;
function __construct() {
parent::__construct('localhost', 'michal', 'saba9811', 'test');
}
public function loginUser($login, $pass) {
$this->result = parent::runQuery("SELECT * FROM users WHERE name = '" . $login . "' AND pass='" . $pass . "'");
var_dump($this->result);
}
}
try {
$login = $_POST['login'];
$pass = $_POST['pass'];
$log = new login();
$log->loginUser($login, $pass);
} catch (Exception $e) {
echo $e->getMessage();
}
答案 0 :(得分:2)
您的runQuery()
函数无法返回任何内容 -
function runQuery($query) {
$this->last_query_result = $this->conn->query($query);
if (!$this->last_query_result) {
$this->setError("Nie udalo sie wykonac zapytania: " . $this->conn->error);
}
}
因此,当您尝试将返回值分配给另一个变量时,它无需分配任何内容:
$this->result = parent::runQuery("SELECT * FROM users WHERE name = '" . $login . "' AND pass='" . $pass . "'");
从$this->last_query_result
获取您的查询结果或重构您的代码。或者只是runQuery()
返回$this->last_query_result
,但这有点多余。