总是出现错误:(在非对象错误上调用成员函数bind_param())
。
我认为我的脚本无法连接到数据库。 db只有3个字段,id,email,密码。请提供任何帮助。
数据库.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);
}
}
?>
用户.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();
登录.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>
最佳答案
您需要在您的类中提供该属性:
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.
关于php - 似乎无法从数据库获取电子邮件和密码来登录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26248553/