PHP and SQLServer Connection

Posted on

Question :

I’m trying to make a connection to SQLServer and PHP
But the page returns me the following error:

  Warning: mssql_connect () [function.mssql-connect]: Unable to connect to server: 192.168.2.7 SRVDOC DOCSYSTEMSCAN in C: wamp www connection.php on line 2

  
  

Warning: mssql_select_db () expects parameter 2 to be resource, boolean given in C: wamp www connection.php on line 3

The current code is:

  

<?php
    $con = mssql_connect("192.168.2.7SRVDOCDOCSYSTEMSCAN", "sa", "minhasenha");
    mssql_select_db("fd_585b0f87", $con);
 ?>

I’m breaking my head but I do not know what could be … Any suggestions?
Thank you.

    

Answer :

Friend, try following the template proposed in the official PHP manual page:

$serverName = "SRVDOCDOCSYSTEMSCAN"; //serverNameinstanceName
$connectionInfo = array( "Database"=>"fd_585b0f87", "UID"=>"sa", "PWD"=>"minhasenha");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

Reference: link

Or try this way with the “mssql_connect” function

$server = 'SRVDOCDOCSYSTEMSCAN';
$link = mssql_connect($server, 'sa', 'minhasenha');

Reference: link

Good luck!

    

According to what is written in the mssql_select_db function documentation a likely cause of this error may be the underscore contained in the database name.

  

To escape the name of a database that contains spaces, hyphens (“-“), or any other exceptional characters, the name of the database must be enclosed in square brackets, as shown in the example below. This technique should also be applied when selecting a database name that contains a reserved word (such as primary ).

To escape the character put fd_585b0f87 in brackets, like this:

 

<?php
    $con = mssql_connect("192.168.2.7SRVDOCDOCSYSTEMSCAN", "sa", "minhasenha") 
    or die ("Erro ao conectar-se ao BD: ".mssql_get_last_message());
    mssql_select_db('[fd_585b0f87]', $con);
?>

    

You could try using PDO to SQLServer

<?php
  try {
    $hostname = "myhost";
    $port = 10060;
    $dbname = "tempdb";
    $username = "dbuser";
    $pw = "password";
    $dbh = new PDO ("dblib:host=$hostname:$port;dbname=$dbname","$username","$pw");
  } catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "n";
    exit;
}

    

Leave a Reply

Your email address will not be published. Required fields are marked *