GrahamNorton
GrahamNorton

Reputation: 121

Connecting SQL server DB to A PHP web application using Wamp

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

Upvotes: 0

Views: 269

Answers (2)

Zhorov
Zhorov

Reputation: 29943

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;
?>

Upvotes: 1

Silvio Delgado
Silvio Delgado

Reputation: 6975

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

Upvotes: 0

Related Questions