In Web development, the combination of PHP and MySQL is very common. However, in some cases, we need to connect to other types of databases, such as SQL Server. In this article, we will cover five different ways to connect to SQL Server using PHP.
PDO Driver
PHP Data Objects (PDO) is a very powerful database in PHP Access the abstraction layer. It allows separation of database code from application code, thereby improving portability and maintainability. To connect to SQL Server we need to enable the PDO_MSSQL extension. The following is a basic PDO connection example:
$serverName = "localhost"; $database = "myDB"; $username = "myUsername"; $password = "myPassword"; try { $conn = new PDO("sqlsrv:server=$serverName;database=$database", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); }
SQLSRV extension
$serverName = "localhost"; $database = "myDB"; $username = "myUsername"; $password = "myPassword"; $connectionInfo = array( "Database"=>$database, "UID"=>$username, "PWD"=>$password); $conn = sqlsrv_connect( $serverName, $connectionInfo); if( $conn ) { echo "Connected successfully"; } else { echo "Connection failed: " . sqlsrv_errors(); }
ODBC API
$serverName = "localhost"; $database = "myDB"; $username = "myUsername"; $password = "myPassword"; $dsn = "Driver={SQL Server};Server=$serverName;Database=$database;"; $conn = odbc_connect($dsn, $username, $password); if($conn) { echo "Connected successfully"; } else { echo "Connection failed"; }
mssql extension
$serverName = "localhost"; $database = "myDB"; $username = "myUsername"; $password = "myPassword"; $conn = mssql_connect($serverName, $username, $password); if($conn) { echo "Connected successfully"; } else { echo "Connection failed"; }
$serverName = "localhost"; $database = "myDB"; $username = "myUsername"; $password = "myPassword"; $dsn = "odbc:Driver={SQL Server};Server=$serverName;Database=$database;"; $conn = new PDO($dsn, $username, $password); if($conn) { echo "Connected successfully"; } else { echo "Connection failed"; }
The above are five different ways to connect PHP and SQL Server. You can choose one of them based on your specific requirements and server environment. Whichever method you choose, be sure to use a secure connection and the correct credentials to protect your data.
The above is the detailed content of A brief analysis of five methods of connecting SQL Server with PHP. For more information, please follow other related articles on the PHP Chinese website!