Php database connection with sql server

PDO_SQLSRV DSN

Specifies whether the connection is assigned from a connection pool (1 or true ) or not (0 or false ).

Specifies whether the communication with SQL Server is encrypted (1 or true ) or unencrypted (0 or false ).

Specifies the server and instance of the database’s mirror (if enabled and configured) to use when the primary server is unavailable.

Specifies the number of seconds to wait before failing the connection attempt.

Disables or explicitly enables support for multiple active Result sets (MARS).

Specifies whether to use SQL-92 rules for quoted identifiers (1 or true ) or to use legacy Transact-SQL rules (0 or false ).

The name of the database server.

Specifies the path for the file used for trace data.

Specifies whether ODBC tracing is enabled (1 or true ) or disabled (0 or false ) for the connection being established.

Specifies the transaction isolation level. The accepted values for this option are PDO::SQLSRV_TXN_READ_UNCOMMITTED, PDO::SQLSRV_TXN_READ_COMMITTED, PDO::SQLSRV_TXN_REPEATABLE_READ, PDO::SQLSRV_TXN_SNAPSHOT, and PDO::SQLSRV_TXN_SERIALIZABLE.

Specifies whether the client should trust (1 or true ) or reject (0 or false ) a self-signed server certificate.

Specifies the name of the computer for tracing.

Examples

Example #1 PDO_SQLSRV DSN examples

The following example shows how to connecto to a specified MS SQL Server database:

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

The following example shows how to connect to a MS SQL Server database on a specified port:

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

The following example shows how to connecto to a SQL Azure database with server ID 12345abcde. Note that when you connect to SQL Azure with PDO, your username will be UserName@12345abcde (UserName@ServerId).

$c = new PDO("sqlsrv:Server=12345abcde.database.windows.net;Database=testdb", "UserName@12345abcde", "Password");

Источник

sqlsrv_connect

Opens a connection to a Microsoft SQL Server database. By default, the connection is attempted using Windows Authentication. To connect using SQL Server Authentication, include «UID» and «PWD» in the connection options array.

Parameters

The name of the server to which a connection is established. To connect to a specific instance, follow the server name with a backward slash and the instance name (e.g. serverName\sqlexpress).

An associative array that specifies options for connecting to the server. If values for the UID and PWD keys are not specified, the connection will be attempted using Windows Authentication. For a complete list of supported keys, see » SQLSRV Connection Options.

Return Values

A connection resource. If a connection cannot be successfully opened, false is returned.

Examples

Example #1 Connect using Windows Authentication.

$serverName = «serverName\\sqlexpress» ; //serverName\instanceName

// Since UID and PWD are not specified in the $connectionInfo array,
// The connection will be attempted using Windows Authentication.
$connectionInfo = array( «Database» => «dbName» );
$conn = sqlsrv_connect ( $serverName , $connectionInfo );

if( $conn ) echo «Connection established.
» ;
>else echo «Connection could not be established.
» ;
die( print_r ( sqlsrv_errors (), true ));
>
?>

Example #2 Connect by specifying a user name and password.

$serverName = «serverName\\sqlexpress» ; //serverName\instanceName
$connectionInfo = array( «Database» => «dbName» , «UID» => «userName» , «PWD» => «password» );
$conn = sqlsrv_connect ( $serverName , $connectionInfo );

if( $conn ) echo «Connection established.
» ;
>else echo «Connection could not be established.
» ;
die( print_r ( sqlsrv_errors (), true ));
>
?>

Example #3 Connect on a specified port.

$serverName = «serverName\\sqlexpress, 1542» ; //serverName\instanceName, portNumber (default is 1433)
$connectionInfo = array( «Database» => «dbName» , «UID» => «userName» , «PWD» => «password» );
$conn = sqlsrv_connect ( $serverName , $connectionInfo );

if( $conn ) echo «Connection established.
» ;
>else echo «Connection could not be established.
» ;
die( print_r ( sqlsrv_errors (), true ));
>
?>

Notes

By default, the sqlsrv_connect() uses connection pooling to improve connection performance. To turn off connection pooling (i.e. force a new connection on each call), set the «ConnectionPooling» option in the $connectionOptions array to 0 (or false ). For more information, see » SQLSRV Connection Pooling.

The SQLSRV extension does not have a dedicated function for changing which database is connected to. The target database is specified in the $connectionOptions array that is passed to sqlsrv_connect. To change the database on an open connection, execute the following query «USE dbName» (e.g. sqlsrv_query($conn, «USE dbName»)).

See Also

  • sqlsrv_close() — Closes an open connection and releases resourses associated with the connection
  • sqlsrv_errors() — Returns error and warning information about the last SQLSRV operation performed
  • sqlsrv_query() — Prepares and executes a query

Источник

Шаг 3. Подтверждение концепции: подключение к SQL с помощью PHP

Эта функция OpenConnection вызывается перед выполнением всех последующих функций.

 function OpenConnection() < $serverName = "tcp:myserver.database.windows.net,1433"; $connectionOptions = array("Database"=>"AdventureWorks", "Uid"=>"MyUser", "PWD"=>"MyPassword"); $conn = sqlsrv_connect($serverName, $connectionOptions); if($conn == false) die(FormatErrors(sqlsrv_errors())); return $conn; > 

Шаг 2. Выполнение запроса

Функция sqlsrv_query может использоваться для извлечения результирующего набора из запроса к базе данных SQL. Эта функция фактически принимает любой запрос и объект подключения, а затем возвращает результирующий набор для итеративного перебора с помощью sqlsrv_fetch_array().

 function ReadData() < try < $conn = OpenConnection(); $tsql = "SELECT [CompanyName] FROM SalesLT.Customer"; $getProducts = sqlsrv_query($conn, $tsql); if ($getProducts == FALSE) die(FormatErrors(sqlsrv_errors())); $productCount = 0; while($row = sqlsrv_fetch_array($getProducts, SQLSRV_FETCH_ASSOC)) < echo($row['CompanyName']); echo("
"); $productCount++; > sqlsrv_free_stmt($getProducts); sqlsrv_close($conn); > catch(Exception $e) < echo("Error!"); >>

Шаг 3. Вставка строки

В этом примере показано, как безопасно выполнить инструкцию INSERT и передать параметры. Значения параметров защищают приложение от внедрения кода SQL.

 function InsertData() < try < $conn = OpenConnection(); $tsql = "INSERT SalesLT.Product (Name, ProductNumber, StandardCost, ListPrice, SellStartDate) OUTPUT" . " INSERTED.ProductID VALUES ('SQL Server 1', 'SQL Server 2', 0, 0, getdate())"; //Insert query $insertReview = sqlsrv_query($conn, $tsql); if($insertReview == FALSE) die(FormatErrors( sqlsrv_errors())); echo "Product Key inserted is :"; while($row = sqlsrv_fetch_array($insertReview, SQLSRV_FETCH_ASSOC)) < echo($row['ProductID']); >sqlsrv_free_stmt($insertReview); sqlsrv_close($conn); > catch(Exception $e) < echo("Error!"); >> 

Шаг 4. Откат транзакции

Этот пример кода демонстрирует использование транзакций, в которых можно:

  • начать транзакцию;
  • вставить строку данных, обновить другую строку данных;
  • зафиксировать транзакцию, если запросы на вставку и обновление выполнены успешно, или откатить транзакцию, если один из запросов вызвал ошибку.
 function Transactions() < try < $conn = OpenConnection(); if (sqlsrv_begin_transaction($conn) == FALSE) die(FormatErrors(sqlsrv_errors())); $tsql1 = "INSERT INTO SalesLT.SalesOrderDetail (SalesOrderID,OrderQty,ProductID,UnitPrice) VALUES (71774, 22, 709, 33)"; $stmt1 = sqlsrv_query($conn, $tsql1); /* Set up and execute the second query. */ $tsql2 = "UPDATE SalesLT.SalesOrderDetail SET OrderQty = (OrderQty + 1) WHERE ProductID = 709"; $stmt2 = sqlsrv_query( $conn, $tsql2); /* If both queries were successful, commit the transaction. */ /* Otherwise, rollback the transaction. */ if($stmt1 && $stmt2) < sqlsrv_commit($conn); echo("Transaction was commited"); >else < sqlsrv_rollback($conn); echo "Transaction was rolled back.\n"; >/* Free statement and connection resources. */ sqlsrv_free_stmt( $stmt1); sqlsrv_free_stmt( $stmt2); > catch(Exception $e) < echo("Error!"); >> 

Источник

sqlsrv_connect

Creates a connection resource and opens a connection. By default, the connection is attempted using Windows Authentication.

Syntax

 sqlsrv_connect( string $serverName [, array $connectionInfo]) 

Parameters

$serverName: A string specifying the name of the server to which a connection is being established. An instance name (for example, «myServer\instanceName») or port number (for example, «myServer, 1521») can be included as part of this string. For a complete description of the options available for this parameter, see the Server keyword in the ODBC Driver Connection String Keywords section of Using Connection String Keywords with SQL Native Client.

Beginning in version 3.0 of the Microsoft Drivers for PHP for SQL Server, you can also specify a LocalDB instance with «(localdb)\instancename» . For more information, see Support for LocalDB.

Also beginning in version 3.0 of the Microsoft Drivers for PHP for SQL Server, you can specify a virtual network name, to connect to an Always On availability group. For more information about Microsoft Drivers for PHP for SQL Server support for Always On availability groups, see Support for High Availability, Disaster Recovery.

$connectionInfo [OPTIONAL]: An associative array that contains connection attributes (for example, array(«Database» => «AdventureWorks»)). See Connection Options for a list of the supported keys for the array.

Return Value

A PHP connection resource. If a connection cannot be successfully created and opened, false is returned.

Remarks

If values for the UID and PWD keys are not specified in the optional $connectionInfo parameter, the connection will be attempted using Windows Authentication. For more information about connecting to the server, see How to: Connect Using Windows Authentication and How to: Connect Using SQL Server Authentication.

Example

The following example creates and opens a connection using Windows Authentication. The example assumes that SQL Server and the AdventureWorks database are installed on the local computer. All output is written to the console when the example is run from the command line.

 $uid, "PWD" => $pwd, "Database"=>"AdventureWorks"); */ $serverName = "(local)"; $connectionInfo = array( "Database"=>"AdventureWorks"); $conn = sqlsrv_connect( $serverName, $connectionInfo); if( $conn ) < echo "Connection established.\n"; >else < echo "Connection could not be established.\n"; die( print_r( sqlsrv_errors(), true)); >//----------------------------------------------- // Perform operations with connection. //----------------------------------------------- /* Close the connection. */ sqlsrv_close( $conn); ?> 

Источник

Читайте также:  Java 8 144 x64
Оцените статью