Eugen
Eugen

Reputation: 1543

How to connect to SQL Server database through PHP?

I'm building a web-service for an Android application that needs to connect to a SQL Server database. I'm trying to connect through PHP (WAMP) on my home computer to the SQL Server database.

However, I don't have experience SQL Server and don't know how to proceed. For SQL Server, I'm using default settings and Windows Authentication, so I'm not sure what to type into the connection string.

Below you have my connection:

$connStr = "PROVIDER=SQLOLEDB;SERVER=".$myServer.";UID=".$myUser.";PWD=".$myPass.";DATABASE=".$myDB; 
$conn->open($connStr); //Open the connection to the database

I haven't found a concrete example anywhere so far, so I need to know what the variables $myServer, $myUser etc. need to be in the case of Windows Authentication.

Alternatively, how can I switch to a User-Name and Password Authentication in SQL Server?

LE: Using Microsoft SQL Server 2008 and SQL Server Management Studio

Upvotes: 0

Views: 16745

Answers (5)

karthik
karthik

Reputation: 11

$dbh = new PDO("sqlsrv:Server=$hostdb;Database=$dbname", $usr, $psw);

Upvotes: 0

karthik
karthik

Reputation: 11

In a related note, the same fate awaits the mysql* extensions if people will ever stop insisting on using them (and the terrible "tutorial" sites stop advocating them) instead of the vastly superior PDO extension. – rdlowrey Feb 12 '12 at 14:58

Upvotes: 0

iDifferent
iDifferent

Reputation: 2200

Microsoft made a driver for PHP, but I think it's better to go with PDO.

You can use PDO_SQLSRV:

$dbh = new PDO("sqlsrv:Server=$hostdb;Database=$dbname", $usr, $psw);

Or use PDO_DBLIB (not available on Windows since PHP 5.3):

$dbh = new PDO("dblib:host=$hostdb;dbname=$dbname", $usr, $psw);       

Upvotes: 2

AMayer
AMayer

Reputation: 355

According to: http://www.php.net/manual/en/function.mssql-connect.php,

mssql_connect($servername, $username, $password)

is how you connect to a Microsoft SQL database.

Upvotes: -1

Dmitry Kudryavtsev
Dmitry Kudryavtsev

Reputation: 17584

PDO is the accepted way to connected to different databases in PHP. It also have a driver for MS-SQL

Here is an example (From PDO MSSQL)

$con = new PDO("sqlsrv:Server=localhost;Database=testdb", "UserName", "Password");

Upvotes: 4

Related Questions