Several ways to connect php to an mssql database

  • 2020-05-30 19:30:00
  • OfStack

First, in the php.ini file; extension = php_pdo_mssql. dll; extension= php_pdo_odbc.dll the semicolon before php_pdo_odbc.dll is removed to determine which way to connect mssql. Be careful to restart the service for it to take effect.

1. Establish a connection

1, odbc

First, set up odbc on the server where the php program resides. There is a difference between 32-bit and 64-bit operating systems. The 32-bit data source (odbc) is managed directly from the control panel, while the 64-bit one runs C:\Windows\SysWOW64\ odbcad32.exe

Set it from inside here. Note: this is only the case where the database server is set to 32, and the data source is set to both 32 and 64 bits. As long as the two servers set up the data source bit 1 send.

Below is the odbc connection setup code.


$con = odbc_connect('odbc The name of the ',' The user name ',' password ');

2. Connect to mssql2000


$con = mssql_connect(' Database address ',' The user name ',' password ');

3. Connect mssql2008


$connectionInfo =  array("UID"=> The user name ,"PWD"=> password ,"Database"=>" Database name ");
$con = sqlsrv_connect(  Database address ,$connectionInfo);

2. Enter the query code

This is all one, can be written directly, can also be copied from mssql after verification. Simply put, you assign an sql statement to a variable.

Similar to the following code


$query = "SELECT top 12 *  Database name  order by id desc";

3. Set up the query and fetch the data

1, odbc


$result = odbc_do($con,$query);
while(odbc_fetch_row($result))
{
    $ The variable name  = odbc_result($result, " The field names ");
}

2. Connect to mssql2000

$result = mssql_query($con, $query);
while($row =mssql_fetch_array($result))
{
    $ The variable name  = $row[" The field names "];
}

3. Connect to mssql2008

$result = sqlsrv_query($con, $query);
while($row = sqlsrv_fetch_array($result))
{
    $ The variable name  = $row[" The field names "];
}

The sqlsrv library is no longer shipped with php 5.3 and later. So download it from Microsoft.

4. Close the connection

It doesn't make any difference, it's odbc_close(); And mssql_close () and sqlsrv_close ();

The php connection to mssql is 1 less than the mssql connection, but it's enough. Specific functions can be referred to the official php manual


Related articles: