Home > Software engineering >  How do I connect to SQL server with PHP?
How do I connect to SQL server with PHP?

Time:12-16

I work with xampp PHP 8.1 I'm trying to connect to SQL Server. I downloaded the drivers, but when starting xampp I get the message (in the log file) that the drivers are not found. I have no idea what the problem is, because the extension file path is correct, the drivers are correct, but they won't load.

CodePudding user response:

To connect to a SQL Server database using PHP, you can use the sqlsrv_connect() function.

an exaple:

$serverName = "serverName\instanceName";
$databaseName = "databaseName";

$connectionOptions = array(
  "Database" => $databaseName,
  "Uid" => "username",
  "PWD" => "password"
);

$conn = sqlsrv_connect($serverName, $connectionOptions);

if ($conn) {
  // Connection was successful
} else {
  // Connection failed
  die(print_r(sqlsrv_errors(), true));
}

CodePudding user response:

In order to connect with SQL database, you need your given DB username, password and PHP sqlsvr_connect() function.

$serverName = "serverName\\sqlexpress"; //serverName\instanceName
$connectionInfo = array( "Database"=>"dbName", "user_id"=>"your_user_name", "passwod"=>"your_password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Connection was successful! <br />";
}else{
     echo "Connection was not successful! <br />";
     die( print_r( sqlsrv_errors(), true));
}
  • Related