How to Use PHP to Connect to SQL Server

Using PHP connect Microsoft SQL Server 2014

First you need to install the correct SQL-server driver for you php version.
Here is a link to install SQL Driver for php 7.3:

https://learn.microsoft.com/en-us/sql/connect/php/download-drivers-php-sql-server?view=sql-server-ver15

Then you need to change your script of php connection. Now looks like you are trying to connect to MySQL instead of SQL-Server.
Here is a script that I used before:

<?php
$serverName = 'x.x.x.x';
$connectionInfo = array('Database'=>'schema-name','UID'=>'user','PWD'=>'password');
$conn=sqlsrv_connect($serverName,$connectionInfo);

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

Where x.x.x.x is the IP address of your SQL-Server and 'user' and 'password' must be your authentication info.

Connect to SQL Server using PHP?

Consider using PHP's Data Objects (PDO) to connect to SQL Server (in fact you can use it to connect to MySQL or any other database).

Using the MSSQL sqlsrv API (various dlls must be set):

<?php

$server = 'servername';
$database = 'databasename';
$username = 'username';
$password = 'pass';

try {
$conn = new PDO("sqlsrv:Server=$server;Database=$database",
$user, $password);
}
catch(PDOException $e) {
echo $e->getMessage()."\n";
exit;
}

?>

Using the ODBC Driver or DSN API (requiring MSSQL ODBC Driver installed which usually ships with database or Windows in general):

<?php

$server = 'servername';
$database = 'databasename';
$username = 'username';
$password = 'pass';

try {
$dbh = new PDO("odbc:Driver={SQL Server};Server=$server;
database=$database",$username,$password);
}
catch(PDOException $e) {
echo $e->getMessage()."\n";
exit;
}

?>

Connect PHP to SQL Server on windows

The mssql* extension has been removed in PHP 7.

https://www.php.net/manual/en/function.mssql-connect.php

You should consider PDO instead.

edit:

PDO for MSSQL requires the appropriate client libraries, which you will find here:
https://learn.microsoft.com/en-us/sql/connect/php/download-drivers-php-sql-server?view=sql-server-2017

Don't let yourself get confused by the version numbers (it's not the PHP version...) check out the description, some drivers are for specific MSSQL server versions only.

Also mind the examples:
https://learn.microsoft.com/en-us/sql/connect/php/download-drivers-php-sql-server?view=sql-server-2017



Related Topics



Leave a reply



Submit