0

I have searched through many posts trying to find an answer but get nowhere. I am trying to establish a connection to and Sql Server DB through my PHP web application using WAMP.

What I have tried:

  1. I downloaded the sql drivers for PHP 7 and 7.1 and tried them with the corresponding PHP versions
  2. I made sure to restart all services after updating the php.ini file.
  3. I haveinstalled the SQLSRV40.EXE and updated the php.ini with:
    • extension=php_pdo_sqlsrv_7_ts_x64.dll
    • extension=php_pdo_sqlsrv_7_nts_x64.dll

I did not though that even though these are added in the php.ini they were not in the php> php extentions list - not sure why

This is my code below allow with the error

<?php
    $serverName="DESKTOP-0KNJ0KP";
    $connectionInfo=array("Database"=>"SPMS_db",);
    $conn=sqlsrv_connect($serverName,$connectionInfo);

    if ($conn) {
        echo "Connected.<br />";
    } else {
        echo "Connection failed.<br />";
        die( print_r( sqlsrv_errors(), true));
    }
?>

enter image description here

I have added context fro PHPinfo()

enter image description here

enter image description here

enter image description here

2
  • whats your phpinfo() say? Commented Apr 13, 2019 at 2:54
  • Most important thing. You need to install ODBC driver in your machine to support SQL server Commented Apr 13, 2019 at 9:25

2 Answers 2

1

You have installed PDO_sqlsrv part of PHP Driver for SQL Server, but your code uses sqlsrv functions. You have two options:

  • install php_sqlsrv_ extensions to make these functions work or
  • rewrite your code to use PDO version of the driver

PHP code using PDO version of PHP Driver for SQL Server:

<?php
# Connection
$server = "DESKTOP-0KNJ0KP";
$database = "SPMS_db";
try {
   $conn = new PDO( "sqlsrv:Server=$server;Database=$database", NULL, NULL);
   $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch( PDOException $e ) {
   die( "Error connecting to SQL Server. ".$e->getMessage() );
}

# End
$conn = null;
?>
Sign up to request clarification or add additional context in comments.

Comments

0

Connecting through PDO library (which is already installed in your server) is easier.

See PDO Book from PHP.NET: https://www.php.net/manual/en/ref.pdo-dblib.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.