始终收到错误:(Call to a member function bind_param() on a non-object error)
。
我认为我的脚本无法连接到数据库。 db只有3个字段,id,email,password。请任何帮助。
database.php中
<?php
class Database {
public function __construct() {
$host = '127.0.0.1';
$user = 'root';
$pass = '';
$name = 'test';
@$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name);
}
}
?>
users.php
<?php
include "database.php";
class Users extends Database {
public function login($email, $password) {
if($stmt = $this->mysqli->prepare("SELECT email, password FROM users WHERE `email` = ? AND `password` = ? LIMIT 1")){
$stmt->bind_param('sssss', $email, $password);
$stmt->execute();
$stmt->bind_result($email, $password);
$stmt->store_result();
if($stmt->num_rows == 1) {
while($stmt->fetch()) {
$_SESSION['email'] == $email;
echo $email;
}
} else {
echo "ERROR";
}
$stmt->close();
$stmt->free_result();
} else {
echo"Something went wrong";
}
}
}
$users = new users();
的login.php
<?php
session_start();
include "php/classes/users.php";
if(isset($_POST['login'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$users->login($email, $password);
}
?>
登录表单
<form action="" method="POST" name="login">
<input type="email" name="email" id="username" placeholder="Vendoseni E-mailin"/><br/>
<input type="password" name="password" id="pass" placeholder="Vendoseni Passwordin"/><br/>
<input type="submit" name='login' value="Kycuni" id="login_btn"/>
</form>
答案 0 :(得分:1)
您需要在班级中提供该属性:
class Database
{
protected $mysqli; // change visibility
private $host = '127.0.0.1';
private $user = 'root';
private $pass = '';
private $name = 'test'; // these guys
public function __construct()
{
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name);
}
}
然后在那个Users类上:
class Users extends Database
{
public function login($email, $password)
{
if($stmt = $this->mysqli->prepare("SELECT email, password FROM users WHERE `email` = ? AND `password` = ? LIMIT 1")){
$stmt->bind_param('ss', $email, $password);
// ^^ only two placeholders! not ssss
$stmt->execute();
$stmt->bind_result($email, $password);
$stmt->store_result();
if($stmt->num_rows == 1) {
while($stmt->fetch()) {
$_SESSION['email'] == $email;
echo $email;
}
} else {
echo "ERROR";
}
$stmt->free_result(); // free the result first, then close
$stmt->close(); // not the other way around.
} else {
echo"Something went wrong";
}
}
}
$users = new Users(); // initialize that particular class.