PHP PDO Microsoft SQL SERVER

Asked

Viewed 679 times

1

Personal I have this class that connects with mysql database, how can I use to connect to microsoft SQL Server ?

<?php

abstract class database {
    /* Método construtor do banco de dados */

    private function __construct() {

    }

    /* Evita que a classe seja clonada */

    private function __clone() {

    }

    /* Método que destroi a conexão com banco de dados e remove da memória todas as variáveis setadas */

    public function __destruct() {
        $this->disconnect();
        foreach ($this as $key => $value) {
            unset($this->$key);
        }
    }

    private static $dbtype = "mysql";
    private static $host = "localhost";
    private static $port = "3306";
    private static $user = "root";
    private static $password = "";
    private static $db = "banco";


    /* Metodos que trazem o conteudo da variavel desejada
      @return   $xxx = conteudo da variavel solicitada */

    private function getDBType() {
        return self::$dbtype;
    }

    private function getHost() {
        return self::$host;
    }

    private function getPort() {
        return self::$port;
    }

    private function getUser() {
        return self::$user;
    }

    private function getPassword() {
        return self::$password;
    }

    private function getDB() {
        return self::$db;
    }

    private function connect() {
        try {
            $this->conexao = new PDO($this->getDBType() . ":host=" . $this->getHost() . ";port=" . $this->getPort() . ";dbname=" . $this->getDB(), $this->getUser(), $this->getPassword());
        } catch (PDOException $i) {
            //se houver exceção, exibe
            die("Erro: <code>" . $i->getMessage() . "</code>");
        }

        return ($this->conexao);
    }

    private function disconnect() {
        $this->conexao = null;
    }

    /* Método select que retorna um VO ou um array de objetos */

    public function selectDB($sql, $params = null, $class = null) {
        $query = $this->connect()->prepare($sql);
        $query->execute($params);

        if (isset($class)) {
            $rs = $query->fetchAll(PDO::FETCH_CLASS, $class) or die(print_r($query->errorInfo(), true));
        } else {
            //$rs = $query->fetchAll(PDO::FETCH_OBJ) or die(print_r($query->errorInfo(), true));
            $rs = $query->fetchAll(PDO::FETCH_OBJ);
        }
        self::__destruct();
        return $rs;
    }

    /* Método insert que insere valores no banco de dados e retorna o último id inserido */

    public function insertDB($sql, $params = null) {
        $conexao = $this->connect();
        $query = $conexao->prepare($sql);
        $query->execute($params);
        $rs = $conexao->lastInsertId() or die(print_r($query->errorInfo(), true));
        self::__destruct();
        return $rs;
    }

    /* Método update que altera valores do banco de dados e retorna o número de linhas afetadas */

    public function updateDB($sql, $params = null) {
        $query = $this->connect()->prepare($sql);
        $query->execute($params);
        $rs = $query->rowCount() or die(print_r($query->errorInfo(), true));
        self::__destruct();
        return $rs;
    }

    /* Método delete que excluí valores do banco de dados retorna o número de linhas afetadas */

    public function deleteDB($sql, $params = null) {
        $query = $this->connect()->prepare($sql);
        $query->execute($params);
        $rs = $query->rowCount() or die(print_r($query->errorInfo(), true));
        self::__destruct();
        return $rs;
    }

}

PS: use the php of xamp and mac osx, I am connecting to a remote sql server....

Obg

  • Put your code here, along with your question. The link will expire over time, and when it does, your question, the way it is, won’t make sense.

  • Okay, I’m sorry

  • Take advantage of the lull and put your attempt and possible mistakes that occurred.

  • The error is drive not found, use the php of xamp on mac, am connecting on a network machine... For now the error is this ...

  • The problem in both answers is that I use php from xamp and on mac

  • And you don’t think that information is important enough to be in your question?

  • vdd, sorry I’ll change ....

Show 3 more comments

1 answer

1


Quick fix, exchange these lines with Sql Server data:

private static $dbtype = "sqlsrv"; //aquivo troca para sqlsrv
private static $host = "ip";
private static $port = "3306";
private static $user = "root";
private static $password = "";
private static $db = "banco";

private function connect() {
    try {
        $this->conexao = new PDO($this->getDBType() . ":Server=" . $this->getHost() . ";port=" . $this->getPort() . ";Database=" . $this->getDB(), $this->getUser(), $this->getPassword());
    } catch (PDOException $i) {
        //se houver exceção, exibe
        die("Erro: <code>" . $i->getMessage() . "</code>");
    }

    return ($this->conexao);
}

Slower, but more extensive solution. Trade all private for protected, so classes that inherit their class can see and modify these methods, and all self:: for Static:: (for you to change the value of the properties and your daughter class to use the modification of it). To better understand self:: and Static:: click at this link

Once these replacements are made, create a new class, and use it to connect to the database

class sqlServerDatabase extends database
{
    private static $dbtype = "sqlsrv"; //aquivo troca para sqlsrv
    private static $host = "ip";
    private static $port = "3306";
    private static $user = "root";
    private static $password = "";
    private static $db = "banco";

private function connect() {
    try {
        $this->conexao = new PDO($this->getDBType() . ":Server=" . $this->getHost() . ";port=" . $this->getPort() . ";Database=" . $this->getDB(), $this->getUser(), $this->getPassword());
    } catch (PDOException $i) {
        //se houver exceção, exibe
        die("Erro: <code>" . $i->getMessage() . "</code>");
    }

    return ($this->conexao);
}
} 

The second method allows you not to keep changing your database class every time you connect to a new database, just inherit it it. This is one of the principles of SOLID, more specifically the O.

In case you do not find the driver, you should enable it in your php.ini, as it is Sql Server in general you will have to install the driver, I would start by this link

  • It’s driver not found... how would I put the drive in the php of xamp ? Because that’s where I’m testing ...

  • I believe you have to download (and put it in php/ext) and adjust it in php.ini There’s a link in the answer that can help

  • the problem I use the xamp and on mac ....

  • the download is . exe does not have this option on mac ....

  • This has already become another question in the OS, its class I have now arranged to install sql server driver on mac, I do not know if it has, difficilmente alguém roda um servidor no mac...

  • Okay, thank you...

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.