Connecting to multiple databases with sqlsrv_connect
Can anyone help me or provide advice on this connection issue I am having. Basically at the moment I can connect to one database at a time. The thing is the data that I am querying is from multiple website (all starting with V1_database.....). For example my database include V1_database_newyork or V1_database_denver etc.
I have created a query like this in Microsoft SQL Server Management Studio which picks up all the database beginning with V1_database:
SELECT name
FROM sys.databases
WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb') AND name LIKE 'V1_database%'
My current code to connect to one of my databases is as follows (this works fine):
<?php
/*data base connection */
$serverName = ".\SQLEXPRESS";
$connectionOptions = array("Database"=>"V1_database_newyork",
"UID"=>"username",
"PWD" => "password");
/* Connect using Windows Authentication */
$conn = sqlsrv_connect($serverName, $connectionOptions);
/* Check whether connnection is established */
if($conn === false)
{
die(print_r(sqlsrv_errors(), true));
}
/* Close the connection. */
sqlsr开发者_开发知识库v_close( $conn);
?>
Can anyone help me adapt this query so the connection string will allow me to query any database with "V1_database%"?
If any of this is at all unclear, please let me know! Any advice will be much appreciated!
Cheers,
Neil
According to the PHP documentation on mssql_connect:
resource mssql_connect ([ string $servername [, string $username [, string $password [, bool $new_link ]]]] )
The return resource must be used in all queries, so connect to MSSQL with this:
$res = mssql_connect ([ string $servername [, string $username [, string $password [, bool $new_link ]]]] )
and use $res
in all queries.
mssql_query ( string $query [, resource $link_identifier [, int $batch_size = 0 ]] )
If you need connections to two database, then use $res1
and $res2
.
A good practice is to make some light class to store not only the connection resource, but other things, like last error.
精彩评论