Use PDO in PHP to connect to the SQL Sever database

0

I try to connect to the Microsoft SQL Server Managament Studio database with PDO but it tells me that an error occurred when connecting to the database. Here I attach the code:

private $conn;

function __construct() {        
} 
/**
 * Establishing database connection
 * @return database connection handler
 */
function connect() {
    include_once dirname(__FILE__) . './Config.php';

    try {
        $this->conn = new PDO('sqlsrv:host='.DB_HOST.';dbname='.DB_NAME, DB_USERNAME, DB_PASSWORD);
        $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

        // returing connection resource
        return $this->conn;

    } catch(PDOException $ex) {

        // if the environment is development, show error details, otherwise show generic message
        if ( (defined('ENVIRONMENT')) && (ENVIRONMENT == 'development') ) {
            echo 'An error occured connecting to the database! Details: ' . $ex->getMessage();
        } else {
            echo 'An error occured connecting to the database!';
        }
        exit;
    }

}
    
asked by rosibel vicent 10.04.2018 в 17:52
source

1 answer

0

In order to guide how to perform the cx of t-sql with pdo in php below attached related source code and the respective URL where you can validate tmb the guidelines that must be enabled in the php.ini file:

<?php

$dsn = 'dblib:host=<ip address>;dbname=<database name>';
$user = 'user id';
$password = 'password';

try
{
    $pdo_object = new PDO($dsn, $user, $password);
}
catch (PDOException $e)
{
    echo 'Connection failed: ' . $e->getMessage();
}

$sql = "SELECT * from <some table>";
$pdo_statement_object = $pdo_object->prepare($sql);
$pdo_statement_object->execute();
// $result = $pdo_statement_object->fetch(PDO::FETCH_ASSOC);
$result = $pdo_statement_object->fetchAll();
print_r($result);
?>

Bibliography: link

I hope you find it useful, greetings.

    
answered by 10.04.2018 в 17:57