我在PHP文件中收到此错误。
我的登录功能
<?php
session_start();
include ("../dbConnection.php");
class login {
public $link;
function __construct()
{
$dbc = new dbConnection();
$this->link = $dbc->Connect();
return $this->link;
}
public function get_data($emailid,$password)
{
$q = $this->link->prepare("SELECT id from students WHERE emailid='$emailid' AND password='$password' AND active='Yes'");
$q->execute(array(':emailid'=>$emailid,':password'=>$password));
$counts = $q->fetch();
if($counts['id'] > 0)
{
session_start();
$_SESSION['userlogin'] = $counts['id'];
$encrypt_id1 = $this->encrypt_decrypt('encrypt', $counts['id']);
echo $encrypt_id1;
}
}
}
dbConnection.php
<?php
public class dbConnection {
public $conn;
public $db_host = 'localhost';
public $db_name = 'pte_mock';
public $db_user = 'root';
public $db_pass = '';
public function Connect()
{
try{
$this->conn = new PDO("mysql:host=".$this->db_host.";dbname=".$this->db_name,$this->db_user,$this->db_pass);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
return $this->conn;
}
}
我收到以下声明
的错误"$q = $this->link->prepare("SELECT id from students WHERE emailid='$emailid' AND password='$password' AND active='Yes'");"
错误
"PHP Fatal error: Uncaught Error: Call to a member function prepare() on null"
我不知道这个问题是什么。如果有人知道解决方案,请帮我解决这个问题。提前谢谢。
答案 0 :(得分:0)
定义类时,需要构造函数才能初始化实例变量。
class dbConnection {
public $conn,
$db_host,
$db_name,
$db_user,
$db_pass;
public function __construct()
{
$this->conn = false;
$this->db_host = 'localhost';
$this->db_name = 'pte_mock';
$this->db_user = 'root';
$this->db_pass = '';
}
/* ... */
也无法定义类public
,这会在编译时引发语法错误。
所以你只有class dbConnection {
我不确定这是否会导致问题,但是负责人不能返回值。实际上,它们返回刚创建的实例(对象)。
你已进入班级login
:
function __construct()
{
$dbc = new dbConnection();
$this->link = $dbc->Connect();
// return $this->link; // <--- REMOVE THAT - YOU CANNOT RETURN VALUES HERE!
}
当您致电$lgn = new login()
时,系统会调用__construct()
函数,并进入$lgn
类login
的新实例。如果构造函数返回任何被丢弃的内容!
所以你应该这样重构你的代码:
$lgn = new login(); // <--- returns a new instance of the class login
$the_link= $lgn->link; // <--- this way you access `link` instance variable
最后这个
$q = $this->link->prepare("SELECT id from students WHERE emailid='$emailid' AND password='$password' AND active='Yes'");
在将值注入查询而不是指定占位符时,不是构建预准备语句的正确方法。
该行应以这种方式编写
$q = $this->link->prepare("SELECT id from students WHERE emailid=:$emailid AND password=:password AND active='Yes'");
答案 1 :(得分:-1)
替换你的代码的这一部分
$q = $this->link->prepare("SELECT id from students WHERE emailid='$emailid' AND password='$password' AND active='Yes'");
$q->execute(array(':emailid'=>$emailid,':password'=>$password));
用这个:
$q = $this->link->prepare("SELECT id FROM students WHERE emailid = :emailid AND password = :password AND active = 'Yes'");
$q->execute(array(':emailid'=>$emailid,':password'=>$password));