PDO用户类不会获得发布数据

时间:2013-06-16 13:09:50

标签: php pdo

我已经尝试过我所知道的一切,但它仍然没有用。我无法从我的HTML表单中获取任何发布的数据,我知道它没有从HTML表单中获取数据,因为我试图更改值并在没有表单的情况下执行然后它可以正常工作。

这是我的html表单:

<?php

ob_start();
session_start();

error_reporting(E_ALL);
if (!ini_get('display_errors')) { ini_set('display_errors', '1');}

include 'classes/user.class.php';
include 'classes/database.class.php';
include 'classes/config.class.php';
include 'classes/bcrypt.class.php';

if(isset($_POST['submitted'])) {
$user = new MonetizeMedia\Classes\User;
$db = new MonetizeMedia\Classes\Database;

$username = $_POST['username'];
$password = $_POST['password'];

$user->username = $username;
$user->password = $password;


if($user->createUser()) {
    echo "DONE!";
}
else
{   
    echo "<br />An error occured while creating your account. Please try later.";
    return;
}

}

?>
<!DOCTYPE html>
<html>
<head>

<meta charset="UTF-8" />

<title>Register</title>

</head>
<body>

<form method="post" action="">
<ul>
<li>
<label for="usn">Username : </label>
<input type="text" name="username" />
</li>

<li>
<label for="passwd">Password : </label>
<input type="password" name="password" />
</li>

<li class="buttons">
<input type="submit" name="submitted" value="Register" />
</li>

</ul>
</form>

</body>
</html>

我的用户类

<?php

namespace MonetizeMedia\Classes;

class User {
private $uid;
private $fields;

public function __construct() {
    $this->uid = null;
    $this->fields = array('username' => '',
                          'password' => '');
}

public function __get($field) {
    if($field == 'uid')
    {
        return $this->uid;
    }
    else
    {
        return $this->fields[$field];
    }
}

public function __set($field, $value) {
    if(array_key_exists($field, $this->fields))
    {
        $this->fields[$field] = $value;
    }
}

public function validateUsername($username) {
    return preg_match('/^[a-zA-Z]{4,15}$/i', $username);
}

public function validateEmailAddr($email) {
    return preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email);     
}

public function getUserById($id) {
    $user = new \MonetizeMedia\Classes\User;
    $db = new \MonetizeMedia\Classes\Database;

    $sql = "SELECT * FROM users WHERE uid = :uid";
    $db->prepare($sql);
    $db->bindParam(":uid", $id);
    $row = $db->fetchAll();

    $user->uid = $row['uid'];
    $user->username = $row['username'];
    $user->password = $row['password'];
    return $user; 
}

public function getByUsername($username) {
    $user = new \MonetizeMedia\Classes\User;
    $db = new \MonetizeMedia\Classes\Database;

    $sql = "SELECT * FROM users WHERE username = :username";
    $db->prepare($sql);
    $db->bindParam(":username", $username);
    $row = $db->fetchAll();

    $user->uid = $row['uid'];
    $user->username = $row['username'];
    $user->password = $row['password'];
    return $username;
}

public function createUser() {
    try {

    $username = null;
    $password = null;

    $db = new \MonetizeMedia\Classes\Database();    
    $bcrypt = new \MonetizeMedia\Classes\Bcrypt(15);

    /*** query ***/
    $sql = 'INSERT INTO users(username, password) VALUES(:username, :password)';

    /*** prepare the select statement ***/
    $db->prepare($sql);

    /*** bind the parameters ***/
    $db->bindParam(":username", $username);
    $db->bindParam(":password", $bcrypt->hash($password));
    //$db->bindParam(":username", "test");
    //$db->bindParam(":password", $bcrypt->hash("test"));

    /*** execute the prepared statement ***/
    $db->execute();

    $result = $db->fetchAll();

    return $result;

    } catch ( \PDOException $e ) {
        return $e->getMessage();
    }

}


}

?>

这是我的数据库类:

<?php

namespace MonetizeMedia\Classes;
use PDO;

class Database {
private $db = array();
private $dbh;
private $error;
private $stmt;


public function __construct() {
    $Config = new \MonetizeMedia\Classes\Config;
    $this->db['username'] = $Config->DB_USERNAME;
    $this->db['password'] = $Config->DB_PASSWORD;
    $this->db['database'] = $Config->DB_DATABASE;
    $this->db['server']   = $Config->DB_SERVER;
    $this->db['port']     = $Config->DB_PORT;
    $this->db['encoding'] = $Config->DB_ENCODING;

    try {
        /* Create a connections with the supplied values */
        $this->dbh = new \PDO("mysql:host={$this->db['server']};dbname={$this->db['database']};port={$this->db['port']};charset={$this->db['encoding']}", $this->db['username'], $this->db['password']);
        $this->dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); // throw exceptions on errors (default: stay silent) 
        $this->dbh->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false); // important! use actual prepared statements (default: emulate prepared statements) 
        $this->dbh->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_CLASS); // fetch associative arrays (default: mixed arrays) 
        $this->dbh->setAttribute(\PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8" ); // set encoding to utf8
        } catch( \PDOException $e ) {
        /* If any errors echo the out and kill the script */
        echo "<center><b>[DATABASE] Error - Connection Failed:</b> " . $this->error = $e->getMessage() . "<br/><br/><br/></center>";
        echo "<center><b>We are currently experiencing technical difficulties. We have a bunch of monkeys working really hard to fix the problem.</b></center>";
        die();
        }   
}

public function prepare($sql) {
    try {
        $this->stmt = $this->dbh->prepare($sql);
    } catch ( \PDOException $e ) {
        $e->getMessage();
        // throw new InvalidSQLException("Invalid SQL. Statement could not be prepared.");
    }

}

public function bindParam($param, $value, $type = null) {
    if (is_null($type)) {
        switch (true) {
            case is_int($value):
                $type = PDO::PARAM_INT;
                break;
            case is_bool($value):
                $type = PDO::PARAM_BOOL;
                break;
            case is_null($value):
                $type = PDO::PARAM_NULL;
                break;
            default:
                $type = PDO::PARAM_STR;
                break;
        }
    }
    return $this->stmt->bindParam($param, $value, $type);
}

public function execute() {
    try {
        return $this->stmt->execute();
        } catch ( \PDOException $e ) {
            $e->getMessage();
        }

}

public function fetchAll() {
    $this->execute();
    return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}

public function fetch() {
    $this->execute();
    return $this->stmt->fetch(PDO::FETCH_ASSOC);
}

public function rowCount() {
    return $this->stmt->rowCount();
}

public function lastInsertId() {
    return $this->dbh->lastInsertId();
}

public function beginTransaction() {
    return $this->dbh->beginTransaction();
}

public function endTransaction() {
    return $this->dbh->commit();
}

public function cancelTransaction() {
    return $this->stmt->rollBack();
}

public function debugDumpParams() {
    return $this->stmt->debugDumpParams();
}

public function errorInfo() {
    return $this->dbh->errorInfo();
}

public function countAll($arr) {
    return count($arr);
}


}

?>

如果没有适当的解决方案,我已经在这个问题上坐了10多个小时。

1 个答案:

答案 0 :(得分:0)

究竟什么不起作用? 无论如何,你应该重写你的createUser方法:

$username = null;
$password = null;