致命错误:在第24行的C:\ xampp \ htdocs \ hmslogin \ include \ authenticate.inc中的非对象上调用成员函数prepare()

时间:2015-12-20 10:23:01

标签: php mysql pdo

我使用PDO时遇到问题。登录后我有这个错误报告。

致命错误:在第24行的C:\ xampp \ htdocs \ hmslogin \ include \ authenticate.inc中的非对象上调用成员函数prepare()

脚本是:

<?php
/**
* @file
* Authentication scripts.
*/

/**
* Check if username, password pair exists.
*
* @params string $username
*   The username of the person
* @params string $password
*   The password of the person
*
* @return bool
*   Returns true if the username password pair match. False otherwise.
*/
function check_password($username,$password){
  $sql = "SELECT `role`"
  . " FROM `users`"
  . " WHERE `username` = :username"
  . " AND `password` = :password";
  global $dbh;
  $res = $dbh->prepare($sql);
  $res->bindParam(':username',$username);
  $password = sha1($password);
  $res->bindParam(':password',$password);
  $res->execute();
  if($row = $res->fetch()){
    $_SESSION['user'] = $username;
    $_SESSION['role'] = $row['role'];
    return true;


  }
  return false;
}
/**
* Function to display the login form and authentication details.
*
*/
function display_login_form(){
  global $tpl;

  if(isset($_POST['username']) && isset($_POST['password'])){
    if(check_password($_POST['username'],$_POST['password'])){
      $tpl->msg = "Logged in sucessfully. Refresh page to go home";
      generate_bill();
      return;
    }
    else{
      $tpl->msg = "Username Password combination incorrect";
      $tpl->form = true;
    }
  }
  else{
    $tpl->form = true;
  }
  $tpl->content = $tpl->fetch("./template/login_form.php.tpl");
  $tpl->display("./template/index.php.tpl");

}
/**
* Function to handle the logout from sessions.
*
*/
function logout(){
  unset($_SESSION);
  session_destroy();
  global $tpl;
  $tpl->msg = "Logged out sucessfully";
  display_login_form();
}
/**
* Function to check Role
*
* Function te check if the authenticated user role has permission to access
* A particular sub module.
*
* @params string $perm
*   The perm to be checked against the authenticated user.
*
* @return boolean
*   Returns true if the user is allowed to access a particular function. False
*   otherwise.
*
*/
function check_perms($perm){
  global $auth;
  return in_array($perm,$auth[$_SESSION['role']]);
}

2 个答案:

答案 0 :(得分:2)

您的$dbh变量未引用PDO对象,这解释了错误:Call to a member function prepare() on a non-object。您需要先创建一个对象并引用它:

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

另外,我建议您查看this manual

<强> ADDITION

之后,您应该以与此类似的方式使用此对象:

$res = $dbh->prepare($query);
$res->bindValue(/* parameters */);
$res->execute();

答案 1 :(得分:0)

您的Object尚未初始化。

如果要在单独的类文件或php文件中初始化PDO对象,则应将其包含在当前的php文件中,或者继承您的类文件。

创建PDO对象的方法如下

$dbh = new PDO('mysql:host=<YOURHOST>;dbname=<DBNAME>', 'YOURUSERNAME VARIABLE', 'YOURPASSWORD VARIABLE');