I have a working website running on Unix that connects via VPN to a SQL Server database using dblib.
The connection has been created in years past like this:
$pdo = new PDO('dblib:host=192.168.2.4:1433;dbname=Andover;charset=utf8', 'UserName', 'Password');
$Query= "Select * From tablename";
$Stmt = $pdo->prepare($Query);
The new connection method I've been told to use is as follows:
<?php
$serverName = "192.168.2.4,1433"; //serverName\instanceName, portNumber (default is 1433)
$connectionInfo = array( "Database"=>"Andover", "UID"=>"UserName", "PWD"=>"Password");
$pdo = sqlsrv_connect( $serverName, $connectionInfo);
if( $pdo ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
echo "****************EOF************";
?>
And this seems to work, running through without error.
However, when I try to use a table it fails:
$sql= "SELECT * from TableName";
$stmt = $pdo->prepare($sql);
$stmt->execute();
The error is:
Uncaught Error: Call to a member function prepare() on resource
What do I need to do to be able to access the table?
3条答案
按热度按时间qf9go6mv1#
You are using the
SQLSRV
part of the PHP Driver for SQL Server, which is different from thePDO_SQLSRV
version and is not object oriented. The return value from thesqlsrv_connect()
function is not an object, it's a PHP connection resource orfalse
if a connection cannot be successfully created and opened.In your specific situation you simply need a combination of
sqlsrv_query()
andsqlsrv_fetch_array()
. As is explained in the documentation ... The sqlsrv_query function is well-suited for one-time queries and should be the default choice to execute queries unless special circumstances apply. This function provides a streamlined method to execute a query with a minimum amount of code. The sqlsrv_query function does both statement preparation and statement execution, and can be used to execute parameterized queries... .Of course, a PDO approach is also an option:
wkyowqbh2#
sqlsrv it's not PDO and have different sintax, first argument it's resource of connection to MSSQL, that's why you recieve your error.
Full working code must be like this:
kcwpcxri3#
When you use
sqlsrv_connect()
, it doesn't return a PDO instance but a resource on success, or false on failure.Using the
SQLSRV
API's functions.