سؤال

So I have a register and login sequence complete, but I have to connect to the database inside each of these individually. I am trying to use a separate class that I can simply include to be connected to the database. My hopes are that this will simplify future pages that need a db connection and also it will hide my login information to the database. Here is the code; I left the old code in, just 'commented' it out:


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.";
};

};

?>
هل كانت مفيدة؟

المحلول

you have errors in your code. in DBconn class the constrcut should have double underscores at the beginning __construct.

And the next error is in registersecure.php

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

As a sidenote, this is not the correct way to to get an instance of a connection, either you should close the connection and open it again or you should give a unique name to the connection handler. I personally write my db connection handler class like this:

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
  }
}

then to get a new instance from any other place you just need to include this in that file

require_once 'DBQuery.class.php';

and get a new instance of DBQuery:

$db = DBQuery::getInstance();

also you can pass config params like db name, username, password, etc. as an array to connect to a different db on the fly :)

نصائح أخرى

You haven't made a question. However, I can see that you're addressing your class instance $db as if it was the connection, which it isn't. You still need to get the protected connection property with the getter method.

$query = $db->getConnection()->prepare($sql); 
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top