2

我正在创建一个用户可以登录的网站,他们有自己的个人资料页面,可以在其中更改一些设置。要查看他们的个人资料,他们必须登录。

我有一个注册页面,要求用户输入他们的名字、姓氏、用户名和密码。我想要完成的是一个单页解决方案,用户可以在其中注册/登录/查看他们的个人资料等。

到目前为止,我有这个:

member.php - 这是成员类

<?php

require_once("database.php");

class Member extends DatabaseObject {
    protected static $table_name = "tblMembers";
    var $firstName = null; // initiating the $firstName variable
    var $lastName = null; // initiating the $lastName variable
    var $username = null; // initiating the $username variable
    var $password = null; // initiating the $password variable
    var $reviews = null; // initiating the $reviews variable
    var $type = null; // initiating the $type variable

    function __construct($firstName, $lastName, $username, $password) {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
        $this->username = $username;
        $this->password = $password;
        //$this->insert($firstName, $lastName, $username, $password, $type);
    }

    function set_firstName($firstName) {
        $this->firstName = $firstName;
    }

    function get_firstName() {
        return $this->firstName;
    }

    function set_lastName($lastName) {
        $this->lastName = $lastName;
    }

    function get_lastName() {
        return $this->lastName;
    }

    function get_fullName() {
        if (isset($this->firstName) && isset($this->lastName)) {
            return $this->firstName . " " . $this->lastName;    
        } else {
            return "";
        }
    }

    function set_username($username) {
        $this->username = $username;
    }

    function get_username() {
        return $this->username;
    }

    function set_password($password) {
        $this->password = md5(DB_SALT.$password);
    }

    function get_password() {
        return $this->password;
    }

    public static function authenticate($username="", $password="") { 
        global $database;
        $username = $database->escape_value($username);
        $password = $database->escape_value($password);
        $passwordHash = md5(DB_SALT.$password);

        $sql = "SELECT * FROM tblMembers ";
        $sql .= "WHERE username = '{$username}' ";
        $sql .= "AND passwordHash = '{$passwordHash}' ";
        $sql .= "LIMIT 1";

        $result_array = self::find_by_sql($sql);
        if (!empty($result_array)) {
            //echo "true";
            return array_shift($result_array); // Pulling first element from array
        } else {
            //echo "false";
            return false; // Ability to ask whether we return something
        }

    }

    public function insert($firstName, $lastName, $username, $password) {
        $database = new Database();
        $database->query("INSERT INTO tblMembers VALUES ('','{$firstName}','{$lastName}','{$username}','{$password}','4')");
    }

    // Common Database Methods

    private static function instantiate($record) {
        $object = new self;

        foreach ($record as $attribute=>$value) {
            if ($object->has_attribute($attribute)) {
                $object->$attribute = $value;
            }
        }
        return $object;
    }

    public static function find_all() {
        return self::find_by_sql("SELECT * FROM ".self::$table_name);
    }

    public static function find_by_id($id=0) {
        global $database;
        $result_array = self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE userID={$id} LIMIT 1");
        if (!empty($result_array)) {
            return array_shift($result_array); // Pulling first element from array
        } else {
            return false; // Ability to ask whether we return something
        }
    }   

    public static function find_by_sql($sql="") {
        global $database;
        $result_set = $database->query($sql);
        $object_array = array();
        while ($row = $database->fetch_array($result_set)) {
            $object_array[] = self::instantiate($row);
        }
        return $object_array;
    }

    private function has_attribute($attribute) {
        $object_vars = get_object_vars($this);
        return array_key_exists($attribute, $object_vars);
    }
}

?>

database.php

这是数据库类

<?php
require_once("config.php");
class Database {

    private $connection;
    public $last_query;
    private $magic_quotes_active;
    private $mysql_real_escape_string_exists;

    function __construct() {
        $this->open_connection();
        $this->magic_quotes_active = get_magic_quotes_gpc();
        $this->mysql_real_escape_string_exists = function_exists("mysql_real_escape_string");
    }

    public function open_connection() {
        // Create Database connection
        $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
        if (!$this->connection) {
            die("Database connection failed: " . mysql_error());
        } else {
            $db_select = mysql_select_db(DB_NAME, $this->connection);
            if (!db_select) {
                die("Database selection failed: " . mysql_error());
            }
        }
    }

    public function close_connection() {
        // Closes the connection to the database
        if(isset($this->connection)) {
            mysql_close($this->connection);
            unset($this->connection);
        }
    }

    public function query($sql) {
        $this->last_query = $sql;
        $result = mysql_query($sql, $this->connection);
        $this->confirm_query($result);
        return $result;
    }

    public function escape_value($value) {

        if ($this->mysql_real_escape_string_exists) {           
            if ($this->magic_quotes_active) {
                $value = stripslashes($value);
            }
            $value = mysql_real_escape_string($value);
        } else {
            if (!$this->magic_quotes_active) {
                $value = addslashes($value);
            }
        }
        return $value;
    }

    public function num_rows($result_set) {
        return mysql_num_rows($result_set);
    }

    public function insert_id($result_set) {
        return mysql_insert_id($this->connection);
    }

    public function affected_rows() {
        return mysql_affected_rows($this->connection);
    }

    public function fetch_array($result_set) {
        return mysql_fetch_array($result_set);
    }

    private function confirm_query($result) {
        if (!$result) {
            $output = "Database query failed: " . mysql_error() . "<br />";
            $output .= "Last SQL query: " . $this->last_query;
            die($output);
        }
    }
}


$database = new Database();

?>

与数据库的连接工作正常,参数存储在config.phpDB_SALT.

register.php - 这包含注册表单,但是我想使用 AJAX 提交表单,而不是强制页面刷新的当前 post 方法。任何帮助实现这一点将不胜感激。我不想为此使用 JQuery,因为我不熟悉它,而且我还在学习 JavaScript,所以我不想继续前进。

<?php
require_once("includes/config.php");
if(isset($_POST['submit'])) {
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $username = $_POST['username'];
    $password = $_POST['password'];
    $member = new Member();
    $member->insert($firstName, $lastName, $username, $password);
} else {
?>
<!DOCTYPE html>
<html lang="en-EN">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="css/style.css" media="screen" />
        <link rel="stylesheet" href="css/email_client.css" media="screen" />
        <!--[if !IE 7]>
            <style type="text/css">
                #wrap {display:table;height:100%}
            </style>
        <![endif]-->

        <title>Register</title>
    </head>
    <body>
        <?php include("includes/header.php"); ?>
        <div id="wrap">
            <div id="main">

                <nav>
                    <?php include("includes/nav.php"); ?>
                </nav>

                <div id="stylized" class="myform">
                    <form action="<?php echo $PHP_SELF; ?>" method="post">
                        <span class="label">First Name:</span>&nbsp;<input id="firstName" type="text" name="firstName" class="splash" value="John"><br />
                        <span class="label">Last Name:</span>&nbsp;<input id="lastName" type="text" name="lastName" class="splash" value="Smith"><br />
                        <span class="label">Username:</span>&nbsp;<input id="username" type="text" name="username" class="splash" value="jsmith"><br />
                        <span class="label">Password:</span>&nbsp;<input id="password" type="password" name="password" class="splash" value="pass"><br />
                        <span class="label">Confirm Password:</span>&nbsp;<input id="passwordConfirmation" type="password" name="passwordC" class="splash" value="pass"><br />
                        <input type="submit" value="Register" class="button" name="submit">
                    </form>
                </div>
            </div>
        </div>
        <div id="footer">
            <?php echo COPYRIGHT_STRING; ?>
        </div>  
    </body>
</html>
<?php } ?>

我想结合 AJAX 和 SESSIONS 等技术来存储用户的状态,以便他们的登录是持久的。

我现在正在努力解决的问题是如何处理 register.php 表单提交、创建new Member对象并将所有数据直接插入数据库。

我检查了我们的各种教程,对于这里需要的东西来说都太复杂了,而且,如上所述,我不想使用 jQuery,至少暂时不想。

4

1 回答 1

0

关于ajax的一般思考

你确定你想要一页吗?根据我的经验,登录页面看起来与个人资料页面截然不同,但这是您的选择。

Ajax 主要是通过 JavaScript 加载网站。您可以从这里开始XMLHttpRequest

您可以使用 XMLHttpRequest 加载完整的网站并替换 html-body 的内容,但 ajax 背后的想法是只传输需要传输的内容,即浏览器中网站上需要更改的内容。因此,通常只传输 JSON 数据,或网站上某些 div 容器的 html 数据。您的服务器需要为这些请求做好准备,例如以非常基本的方式:

<?php
// read request data uses http://www.php.net/manual/en/book.filter.php
$firstName = filter_input(INPUT_POST, 'firstName', FILTER_SANITIZE_STRING);
$lastName  = filter_input(INPUT_POST, 'lastName', FILTER_SANITIZE_STRING);
$username  = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password  = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

//create Memeber object and save it
require_once('member.php');
$member = new Member ($firstName, $lastName, $username, $password);
$success = $member->insert();

// answer the request
$data = new stdClass();
if( $success === true ) { 
    // return Success
    $data->success = true;
    print json_encode($data);
    exit();
} else {
    // return error
    $data->success = false;
    $data->message = 'Could not register';
    print json_encode($data);
    exit();
}
exit(-1);
?>

确保您没有以正常方式提交表单,请参见此处

jQuery 让这一切变得更容易,所以也许你想重新考虑不使用它。

PHP 编程

停止var在已弃用的 php 类中使用它,像在 Database 类中一样使用可见性修饰符 ( private, public, protected)

由于您争相使用 OOP,请注意PHP PDO并尝试将其用于您的数据库层

将您的数据库实现为单例,可能更容易,基本上添加:

<?php
// in Database class

/** The Sigleton instance
  * @var Database
  */
private static $instance = false;

/** Singleton Getter for this class.
  * @return Database The singleton instance.
  */
public static getInstance() {
    if(self::$instance === false) {
        self::$instance = new self();
    }
    return self::$instance;
}
?>

并确保您的构造函数受到保护,因此不会创建其他实例。要使用它,请执行以下操作:

<?php
// in Member class

public function insert($firstName, $lastName, $username, $password) {
    // get singleton instance;
    $db = Database::getInstance();

    return $db->query(sprintf(
        "INSERT INTO tblMembers VALUES ('','%s','%s','%s','%s','4')",
        $db->escape_value($this->firstName),
        $db->escape_value($this->lastName),
        $db->escape_value($this->username),
        $db->escape_value($this->password)
    ));
}
?>

希望这有助于您入门。

于 2014-01-18T18:54:24.107 回答