如何在单独的类中处理连接到mysql数据库?

时间:2014-05-01 23:52:04

标签: php mysql class pdo

所以我有一个注册和登录序列完成,但我必须分别连接到每个内部的数据库。我试图使用一个单独的类,我可以简单地包括连接到数据库。我希望这将简化将来需要数据库连接的页面,并且它会将我的登录信息隐藏到数据库中。这是代码;我留下了旧代码,只是评论了#39;它出来了:


DBconn 的     

class DBconn {

protected $dbname;
protected $dbuser;
protected $dbpassword;
protected $dbhost;

protected $connection;

public function _construct($dbhost, $dbname, $dbuser, $dbpass) 
{
    $this->dbname = $dbname;
    $this->dbhost = $dbhost;
    $this->dbuser = $dbuser;
    $this->dbpass = $dbpass;

    $this->connect();
}

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

protected function connect()
{
    $this->connection = new PDO("mysql:host={$this->dbhost};dbname={$this->dbname}", $this->dbuser, $this->dbpass);
}




}
?>


dblogin.php

<?php

$db = new DBconn('localhost','phpproject','carl','pdt1848?')

?>


registersecure.php

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL); ini_set('display_errors', 1);

//db classes
require_once "/home/carlton/public_html/PHPproject/db/DBconn.class.php";
require_once "/home/carlton/public_html/PHPproject/db/dblogin.php";

//phpass 
require_once "/home/carlton/public_html/PHPproject/includes/PasswordHash.php";

if (empty($_POST)){

?>
 <form name="registration" action="registersecure.php" method="POST">
<label for "username">Username: </label>
<input type="text" name="username"/><br />
<label for "password">Password: </label>
<input type="password" name="password"/><br />
<label for "fname">First Name: </label>
<input type="text" name="fname"/><br />
<label for "lname">Last name: </label> 
<input type="text" name="lname"/><br />
<label for "email">Email: </label>
<input type="text" name="email"/><br />
<button type="submit">Submit</button>
</form>
<?php 
}
else{

$form = $_POST;
$username = $form['username'];
$password = $form['password'];
$fname = $form['fname'];
$lname = $form['lname'];
$email = $form['email'];
//$user = 'carl';
//$pass = 'pdt1848?';
$hash_obj = new PasswordHash(8, false);

//check for valid email 
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
   echo "Thank you for using a valid email adress.";
}
else{
   die("Invalid Email, please go back and try again.");
}

// because hashing greatly increases the size of a password, 
// if password is longer than 72 chars it risk DoS attakcs
if (strlen($password)>72){die("Password must be less than 73 characters.");
}

// if the password was hashed correctly it must be longer than 20 char,
// therefore if the hash is less than 20 characters phpass isn't 
$hash = $hash_obj->HashPassword($password);
/*  if (strlen($hash)>=20){
    try{
        $db = new PDO('mysql:host=localhost;dbname=phpproject', $user, $pass);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PODException $e){
        echo 'Something has gone terribly wrong!';
    }*/
$sql = "INSERT INTO users (username, password, fname, lname, email)VALUES(:username, :password, :fname, :lname, :email)";
$query = $db->getConnection->prepare($sql);
$result = $query->execute(array(':username'=>$username, ':password'=>$hash, ':fname'=>$fname,
    ':lname'=>$lname, ':email'=>$email));
//};
if ($result){
    echo "Thanks for registering with us!";
} else {
    echo "Sorry, an error occurred while editing the database. Contact the guy who built this garbage.";
};

};

?>

2 个答案:

答案 0 :(得分:3)

您的代码中存在错误。 在DBconn类中,constrcut在开头__construct时应该有双下划线。

下一个错误发生在registersecure.php

$query = $db->getConnection->prepare($sql); 应该 $query = $db->getConnection()->prepare($sql);

作为旁注,这不是获取连接实例的正确方法,您应该关闭连接并再次打开它,或者您应该为连接处理程序指定唯一的名称。我个人编写我的数据库连接处理程序类,如下所示:

class DBQuery {
  protected static $_connections = array();
  protected $_dbh;

  protected function __construct($dbh = null) {
    if (null !== $dbh) {
      $this->_dbh = $dbh;
    } else {
      $this->_dbh = new PDO(
        sprintf("mysql:host=%s;dbname=%s", DBHOST, DBNAME), 
        DBUSER, DBPASS
      );
    }
    $this->_dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }

  public static function getInstance($config = null) {
    if (null === $config) {
      $hash = "__default__";
      if (!isset(self::$_connections[$hash])) {
        self::$_connections[$hash] = new self();
      }
    } else {
      $hash = sha1(json_encode($config));
      if (!isset(self::$_connections[$hash])) {
        $dbh = new PDO(
          sprintf("mysql:host=%s;dbname=%s", $config->host, $config->name), 
          $config->username, $config->password
        );
        self::$_connections[$hash] = new self($dbh);
      }
    }
    return self::$_connections[$hash];
  }

  public function __call($methodName, $arguments) {
    return call_user_func_array(array($this->_dbh, $methodName), $arguments);
  }

  public function __destruct() {
    $this->_dbh = null; // closes the db connection
  }
}

然后从任何其他地方获取一个新实例,您只需将其包含在该文件中

require_once 'DBQuery.class.php';

获取DBQuery的新实例:

$db = DBQuery::getInstance();

你也可以将数据库名称,用户名,密码等配置参数传递给数组,以便即时连接到不同的数据库:)

答案 1 :(得分:0)

你没有提出问题。但是,我可以看到您正在将类实例$db称为连接,而不是连接。您仍然需要使用getter方法获取受保护的连接属性。

$query = $db->getConnection()->prepare($sql);