0

我有一个登录会话,在我的登录类中,我创建了一个为我获取用户信息的函数。现在,我暂时将其限制为 user_id,因为我想将其保存到数据库中,以便我可以轻松判断哪个用户在我的数据库中发布了什么。

我正在尝试从另一个类(我的 Login 类)访问此功能。

我尝试了两种方法来从网上找到的方法调用这个函数:

$user_id = Login::usersessioninfo();

$login = new Login(); $login->useressioninfo();

但是,当我调用这两种方式中的任何一种时,都会出现以下错误:

Fatal error: Call to a member function prepare() on a non-object in E:\xampp\htdocs\iproject\classes\class.Login.php on line 101

我不明白为什么 PDO 函数现在突然变成非对象了:/

关于我做错了什么的任何想法?准备好的声明很好我已经在自己的班级中单独测试过,但我很难将其传递给另一个班级。

这是我的数据库:

<?php 

# We are storing the information in this config array that will be required to connect to the database.
$config = array(
    'host'      => 'localhost',
    'username'  => 'root',
    'password'  => '',
    'dbname'    => 'imanage'
);
#connecting to the database by supplying required parameters
$pdo = new PDO('mysql:host=' . $config['host'] . ';dbname=' . $config['dbname'], $config['username'], $config['password']);

#Setting the error mode of our db object, which is very important for debugging.
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>

在一个类中,我这样连接到我的数据库:

编辑:添加完整的登录类 *

 <?php
 // Authentication
  require_once 'init.php';

 class Login {

private $pdo;   // This variable will only be accessible from inside this class

public function __construct($database)
     {

       $this->pdo = $database; 

} // end constructor method

public function validatelogin() {

    $_SESSION['formAttempt'] = true;
    if (isset($_SESSION['error'])) {
        unset($_SESSION['error']);
    }
    $_SESSION['error'] = array();

    $required = array("username","password");

    //Check required fields

        foreach ($required as $requiredField) {
            if (!isset($_POST[$requiredField]) || $_POST[$requiredField] == "") {
            $_SESSION['error'][] = $requiredField . " is required.";
        }
    }
    //final disposition
        if (count($_SESSION['error']) > 0) {
            die(header("Location: ../index.php"));
            } else {
                unset($_SESSION['formAttempt']);
            }
    }//end validate login

 function logged_in() {
        if($_SESSION['authorized'] == true) {
            return true;
        } else {
            return false;
        }
    }

    function login_required() {
        if($this->logged_in()) {
            return true;
        } else {
            header("location: ../index.php");  
        }
    }

    public function loginuser() {

        $username = (isset($_POST['username'])) ? $_POST['username'] : '';
        $password = (isset($_POST['password'])) ? $_POST['password'] : '';
            $Blowfish_Pre = '$2a£05$';
        $Blowfish_End = '$';
        $hashed_pass = crypt($password, $Blowfish_Pre . $row['salt'] . $Blowfish_End);
        //$salt = "boo";
        //$pw = crypt($password, $salt);


        $stmt = $this->pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1");
        $stmt->bindParam(":username", $username, PDO::PARAM_STR);
        $stmt->bindParam(":password", $hashed_pass, PDO::PARAM_STR);
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $total = $stmt->rowCount();

                if($total > 0){
                    session_regenerate_id(true);
                    $_SESSION['username'] = $username;
                    $row['name'] = $name;
                    $_SESSION['authorized'] = true;
                    header("location: ../users.php");  
            } else {
            echo "Wrong password or username";
        }

        //old login script.
            //if (!$row)
            //  {
            //      echo "Invaild username or password. Try again"; 
            //  } else {
            //          $_SESSION['authorized'] = true;
            //      $_SESSION['username'] = $username;
            //      header("Location: testloginrequired.php");  
            //  }

    }// end loginuser

    public static function usersessioninfo() {

        $username = $_SESSION['username'];

        $stmt = $this->pdo->prepare("SELECT * FROM users WHERE username = :username");
        $stmt->bindParam(":username", $username, PDO::PARAM_STR);
        $stmt->execute();
                    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
            // i can put this foreach above .. change $row above to $esult and then use for $row for the foreach()
            foreach($result as $row) {
                    $username = $row['username'];
                    $id = $row['id'];
        }

    }

    //public function selectuser() {
        //$username = "test";
        //$password = "password";

    //  $stmt = $this->pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1");
    //  $stmt->bindValue(":username", $username);
        //$stmt->bindValue(":password", $password);
    //  $stmt->execute();
        //          $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    //  foreach($result as $row) {
        //          $username = $row['username'];
            //      $email = $row['email'];
                //  echo $username;
                //echo $password;
                    //echo $email;
                // }//end foreach
        //  } // end function


    }// End login class


  $login = new Login($pdo);
  $login->logged_in();
  $login->login_required();

  if (isset($_POST['submitlogin'])) {
  $login->loginuser();
  }

* 编辑项目类 *

类/class.Project.php

<?php
include ('init.php');

include('class.Login.php');

class Projects extends Login {

private $pdo;   // This variable will only be accessible from inside this class

    public function __construct($database)
         {
           $this->pdo = $database; 

    } // end constructor method

    public function createproject() {
                                        //$login = new Login($pdo)
                                $user_id = $this->usersessioninfo();
                                $project_name = isset($_POST['project_name']) ? $_POST['project_name'] : null;
                                $project_brief = isset($_POST['project_brief']) ? $_POST['project_brief'] : null;
                                $data = array($user_id, $project_name, $project_brief); 
                                $stmta = $this->pdo->prepare("INSERT INTO projects (user_id, project_name, project_brief) VALUES (?, ?, ?)");

    if (isset($_POST['submitproject'])) {   
                   $stmta->execute($data); 
        echo 'Right thats the boring stuff out of the way, lets create some tasks.';
    printf("%d Row inserted.\n", $stmta->rowCount());
        header("refresh:5; url=../users.php"); 
        } else {
        echo "Sorry something we couldn't process your project, you're been redirected to the registration page shortly.";
            header("refresh:5; url=../create.php");
                                        }
    } // end function
} // end projects class
$run = new Projects($pdo);
$run->createproject();
//$login = new Login($this->pdo); 


?>

初始化文件

<?php

 session_start();
 require 'class.Database.php';
   //$errors = array();
?>

创建项目.php

    <?php 
        include('classes/class.Login.php');
        include('header.html');
        $run = new Login($pdo);

    ?>

            <div id="maincontentWrapper">

            <div id="maincontent">
                <div id="contentWrapper"></div><!--End registerWrapper -->
                    <article>
                        <p>Right lets create your project! Fill in a few details...</p>
                    </article>
                <div id="loginform">
                    <div id="registerWrapper">
                    <form id="registerForm" name="registerForm" method="POST" action="classes/class.Projects.php">
                    <h1><span class="log-in">Create a new project</span></h1>
                            <p class="required"><span class="log-in">*Required Fields</span></p>
                            <div id="errorDiv"><?php 
                                if (isset($_SESSION['error']) & isset($_SESSION['formAttempt'])) {
                                        unset($_SESSION['formAttempt']);
                                        print "Errors encountered<br/>\n";
                                        foreach ($_SESSION['error'] as $error) {
                                        print $error . "<br />\n";
                                    } //end foreach
                                    } //end if 
                            ?></div>

                     <p class="float">
                    <label for="password"><i class="icon-lock"></i>Project Name*</label>
                    <input type="text" id="project_name" name="project_name" placeholder="Project Name" class="showpassword"> 
                    <span class="errorFeedback errorSpan" id="nameError">Project name is required</span>
                </p>
                <p class="float">
                    <label for="login"><i class="icon-user"></i>Project brief*</label>
                    <textarea rows="10" class="showpassword" name="project_brief" placeholder="Insert a short brief about your project"></textarea>
                            <span class="errorFeedback errorSpan" id="usernameError">Username is required</span>
                </p>
                <p class="float">
                    <label for="password"><i class="icon-lock"></i>Project Start Date*</label>
                    <input type="text" id="project_start_date" name="project_start_date" placeholder="Project Start Date" class="showpassword"> 
                            <span class="errorFeedback errorSpan" id="passwordError">Password is required</span>
                </p>
                   <p class="float">
                    <label for="password"><i class="icon-lock"></i>Project End Date (Estimate if you can)*</label>
                    <input type="text" id="project_end_date" name="project_end_date" placeholder="Project End Date" class="showpassword"> 
                            <span class="errorFeedback errorSpan" id="password2Error">Passwords dont mat</span>
                </p>
                <p class="clearfix"> 
                    <input type="submit" name="submitproject" value="Register"></form>
                </p>   
                    </div>

                </div>


            </div>
            </div>

            </div>
    <?php 
    include("footer.html");
    ?>
4

2 回答 2

0

根据您发布的信息,我看不到您将 $pdo 对象传递给“登录”类。

你能发布整个登录类吗?

编辑:

我看到你已经发布了完整的“登录”课程。好吧,据我所知,您没有将 $pdo 对象传递给此处的“登录”类:

$user_id = Login::usersessioninfo();

如果您确实执行以下操作,我相信它会起作用:

$login = new Login($pdo);
$login->useressioninfo();
于 2013-09-27T08:59:56.360 回答
0

在 Project.php 中应该是

$login = new Login($this->pdo);

代替

$login = new Login($pdo);

全局 $pdo 不能从类方法中访问。

于 2013-09-27T09:18:38.660 回答