Search code examples
phpsql-serverphp-mssql

cant connect to mssql server or sqlsrv not showing up on phpinfo


I have problem to connect to SQL server. I did all the steps from here and I already changed the php.ini configuration file:

;On windows: 
extension_dir = "D:\xampp\php\ext"

But I still can't connect, my PHP Version is 7.2.11. I tried with mssql_connect() and sqlsrv_connect():

This is my attempt:

<?php
$servername = "1111";
$username = "user";
$password = "123";
$dbname = "DEV";

$connection = mssql_connect($servername, $username, $password);
if (!$connection) {  die('Not connected : ' . mssql_get_last_message());} 
$db_selected = mssql_select_db($dbname, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mssql_get_last_message());
} else{

echo "success";}
?>

Solution

  • MSSQL extension for PHP (mssql_ functions) and PHP Driver for SQL Server (sqlsrv_ functions) are two different extensions for PHP.

    MSSQL extension is not available anymore on Windows with PHP 5.3 or later, so you need to install PHP Driver for SQL Server. You need to download appropriate version of this driver. For PHP 7.2 - version 5.2 or 5.3 (32-bit or 64-bit also depends on PHP version). Also download and install an appropriate ODBC driver.

    Check the configuration with <?php phpinfo();?>. There should be a section with name pdo_sqlsrv (if you use PDO) and/or sqlsrv (without PDO).

    Example:

    <?php
    $server   = '1111';
    $database = 'DEV';
    $uid      = 'user';
    $pwd      = '123';
    
    # SQL Server authentication
    #$cinfo = array(
    #    "Database" => $database,
    #    "UID" => $uid,
    #    "PWD" => $pwd
    #);
    
    # Windows authentication
    $cinfo = array(
        "Database" => $database
    );
    
    $conn = sqlsrv_connect($server, $cinfo);
    if ($conn === false) {
        echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
        exit;
    } else {
        echo "success";
    }
    
    sqlsrv_close($conn);
    ?>