Mysqli PHP fetch_object

时间:2012-01-20 17:38:43

标签: php login mysqli

我在我的网站上使用了一个mysqli登录系统,我在这里包含了以下文件:

(login.php中):

<?php
session_start();
require_once 'classes/Membership.php';
$membership = new Membership();

// If the user clicks the "Log Out" link on the index page.
if(isset($_GET['status']) && $_GET['status'] == 'loggedout') {
    $membership->log_User_Out();
}

// Did the user enter a password/username and click submit?
if($_POST && !empty($_POST['username']) && !empty($_POST['pwd'])) {
    $response = $membership->validate_User($_POST['username'], $_POST['pwd']);
}


?>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

etc.

这是主要的html文件,以下是php文件:

(membership.php);

<?php

require 'Mysql.php';

class Membership {

    function validate_user($un, $pwd) {
        $mysql = New Mysql();
        $ensure_credentials = $mysql->verify_Username_and_Pass($un, $pwd);

        if($ensure_credentials) {
            $_SESSION['status'] = 'authorized';
proposed session variable:  $_SESSION['name'] = 'RESULT';
            header("location: index.php");
        } else return "Please enter a correct username and password";

    } 

    function log_User_Out() {
        if(isset($_SESSION['status'])) {
            unset($_SESSION['status']);

            if(isset($_COOKIE[session_name()])) 
                setcookie(session_name(), '', time() - 1000);
                session_destroy();
        }
    }

    function confirm_Member() {
        session_start();
        if($_SESSION['status'] !='authorized') header("location: login.php");
    }

}
?>

(mysql.php):

<?php

require_once 'includes/constants.php';

class Mysql {
    private $conn;

    function __construct() {
        $this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or 
                      die('There was a problem connecting to the database.');
    }

    function verify_Username_and_Pass($un, $pwd) {

        $query = "SELECT *
                FROM players_login
                WHERE username = ? AND password = ?
                LIMIT 1";

        if($stmt = $this->conn->prepare($query)) {
            $stmt->bind_param('ss', $un, $pwd);
    My Attempt: $row = $query->fetch_object();
            $stmt->execute();


            if($stmt->fetch()) {
                $stmt->close();
                return true;
            }
        }

    }
}

我的查询是正确的,我希望服务器在index.php中回显用户的名称,例如Hello: Jane Thompson,并且能够在向数据库发布任何内容时使用该名称,即:{{1 }}

1 个答案:

答案 0 :(得分:1)

你可以在$ _SESSION中保存用户名和密码,如:

if($_POST && !empty($_POST['username']) && !empty($_POST['pwd'])) {
    $response = $membership->validate_User($_POST['username'], $_POST['pwd']);
    $_SESSION['user'] = $_POST['username'];
}

所以在index.php中你可以打印

<div>Name: <?php echo $_SESSION['user']?></div>