1
votes

I have a db.php file & and init.php to use within my register.php file.

I have a database within MS SQL Server and am trying to connect to it using PDO.

This error is showing and I can't see why. I used the same code to connect to a MySQL db and this inserted the record as should, but doesn't when writing to a MSSQLServer

Fatal error: Uncaught exception 'PDOException' with message 'could not find driver' in C:\ooplr\classes\DB.php:14 Stack trace: #0 C:\ooplr\classes\DB.php(14): PDO->__construct('mssql:host=myserver;...', 'username', 'pwd') #1 C:\ooplr\classes\DB.php(23): DB->__construct() #2 C:\ooplr\classes\Validate.php(8): DB::getInstance() #3 C:\ooplr\register.php(9): Validate->__construct() #4 {main} thrown in C:\ooplr\classes\DB.php on line 14

The db.php page

<?php
    class DB {
public static $instance = null;
private     $_pdo = null,
            $_query = null,
            $_error = false,
            $_results = null,
            $_count = 0;
private function __construct() {
    try {           
        $this->_pdo = new PDO('mssql:host=' . Config::get('mssql/server') . ';dbname=' . Config::get('mssql/db'), Config::get('mssql/username'), Config::get('mssql/password'));
    } catch(PDOExeption $e) {
        die($e->getMessage());
    }
}
public static function getInstance() {
    if(!isset(self::$instance)) {
        self::$instance = new DB();
    }
    return self::$instance;
}
public function query($sql, $params = array()) {
    $this->_error = false;
    if($this->_query = $this->_pdo->prepare($sql)) {
        $x = 1;
        if(count($params)) {
            foreach($params as $param) {
                $this->_query->bindValue($x, $param);
                $x++;
            }
        }
        if($this->_query->execute()) {
            $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_count = $this->_query->rowCount();
        } else {
            $this->_error = true;
        }
    }       
    return $this;
}
public function get($table, $where) {
return $this->action('SELECT *', $table, $where);
}
public function delete($table, $where) {
    return $this->action('DELETE', $table, $where);
}
public function action($action, $table, $where = array()) {
    if(count($where) === 3) {
        $operators = array('=', '>', '<', '>=', '<=');
        $field      = $where[0];
        $operator   = $where[1];
        $value      = $where[2];
        if(in_array($operator, $operators)) {
            $sql = "{$action} FROM {$table} WHERE {$field} {$operator}   ?";
            if(!$this->query($sql, array($value))->error()) {
                return $this;
            }
        }           
        return false;
    }
}
public function insert($table, $fields = array()) {
    $keys   = array_keys($fields);
    $values = null;
    $x      = 1;
    foreach($fields as $value) {
        $values .= "?";
        if($x < count($fields)) {
            $values .= ', ';
        }
        $x++;
    }
    $sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES     ({$values})";
    if(!$this->query($sql, $fields)->error()) {
        return true;
    }
    return false;
}
public function update($table, $id, $fields = array()) {
    $set    = null;
    $x      = 1;
    foreach($fields as $name => $value) {
        $set .= "{$name} = ?";
        if($x < count($fields)) {
            $set .= ', ';
        }
        $x++;
    }
    $sql = "UPDATE users SET {$set} WHERE id = {$id}";
    if(!$this->query($sql, $fields)->error()) {
        return true;
    }
    return false;
}
public function results() {
    return $this->_results;
}
public function first() {
    return $this->_results[0];
}
public function count() {
    return $this->_count;
}
public function error() {
    return $this->_error;
}}?>

The init.php page

  <?php
    session_start();
    $GLOBALS['config'] = array(
'mssql' => array(
    'server' => 'MyServer',
    'username'  => 'MyUsr',
    'password'  => 'Mypwd',
    'db'    => 'dbname'
),
'remember' => array(
    'cookie_name'   => 'hash',
    'cookie_expiry' =>  604800
),
'session' => array(
    'session_name'  => 'user',
    'token_name'    => 'token'
)
    );
    function autoload($class) {
require_once 'classes/' . $class . '.php';
     }
    spl_autoload_register('autoload');
     require_once 'functions/sanitize.php';
    if(Cookie::exists(Config::get('remember/cookie_name'))) {
$hash = Cookie::get(Config::get('remember/cookie_name'));
$hashCheck = DB::getInstance()->get('users_session', array('hash', '=', $hash));
if($hashCheck->count()) {
    $user = new User($hashCheck->first()->user_id);
    $user->login();
}}?>

The register.php page

     <?php
     require 'core/init.php';
     error_reporting (E_ALL);
     ini_set('display_errors', TRUE);
     if(Input::exists()) {
 if(Token::check(Input::get('token'))) {
    $validate = new Validate();
    $validation = $validate->check($_POST, array(
        'username' => array(
            'required' => true,
            'min' => 2,
            'max' => 20,
            'unique' => 'users'),
        'password' => array(
            'required' => true,
            'min' => 6),
        'password_again' => array(
            'required' => true,
            'matches' => 'password'),
        'name' => array(
            'required' => false,
            'min' => 2,
            'max' => 50)
    ));
    if($validation->passed()) {
        $user = new User();
        $salt = Hash::salt(32);
        try {
            $user->create(array(
                'username'  => Input::get('username'),
                'password'  =>   Hash::make(Input::get('password'), $salt),
                'salt'      => $salt,
                'name'      => Input::get('name'),
                'joined'    => getdate(),
                'group'     => 1
            ));
            Session::flash('home', 'You have been registered and can now log in!');
            Redirect::to('index.php');
        } catch(Exception $e) {
            die($e->getMessage());
        }
    } else {
        foreach($validate->errors() as $error) {
            echo $error, '<br>';
        }}}}?>

     <form action="" method="post">

<div class="field">
    <label for="username">Choose a username</label>
    <input type="text" name="username" id="username" value="<?php echo  escape(Input::get('username')); ?>">
</div>

<div class="field">
    <label for="password">Choose a password</label>
    <input type="password" name="password" id="password">
</div>

<div class="field">
    <label for="password_again">Enter your password again</label>
    <input type="password" name="password_again" id="password_again">
</div>

<div class="field">
    <label for="name">Your name</label>
    <input type="text" name="name" id="name" value="<?php echo escape(Input::get('name')); ?>">
</div>

<input type="submit" value="Register">
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
    </form>

How can I get this to connect and send the data?

1
PDO hasn't got the driver for mssql. please see the manual on how to install it. - Wrikken
Thanks, I've managed to get it to connect :-) I'm looking at the hash issue I have now! - Jez

1 Answers

0
votes

You error message says that PHP/PDO could not find a driver for SQL Server. This happens because PDO does not support SQL Server drivers out of the box.

To get SQL Server support you will need to add Microsoft Drivers for PHP for SQL Server to your PHP installation. This will only be possible if you have control over the PHP installation on the server (this is possible on a local server but not possible in a shared hosting environment).

Alternatively, you may consider using PHP's MSSQL Database Extension that does support Microsoft SQL Server. CodeIgniter uses the MSSQL database extension in their MSSQL database driver.