PHP Microsoft SQL Server "Connection failed: No connection could be made because the target machine"

Discussion in 'Databases' started by Jay Shaw, Aug 6, 2019.

  1. Hello,

    I'm using Microsoft SQL Server - not MySQL.

    I made a very basic PHP database connection script that is currently returning this error message:

    Connection failed: No connection could be made because the target machine actively refused it.​

    I believe this maybe related to the firewall blocking my script or something like a missing connector on the server. What can I do about this?

    Thanks, Jason
     
  2. ComputerMan

    ComputerMan Winhost Staff

    We have a sample code that you can try to use. It's located in our knowledge base article here: https://support.winhost.com/kb/a687/sample-code-to-connect-to-an-ms-sql-database-using-php.aspx

    PHP:
    <?php   
    $serverName 
    "SQL Server";   
    $uid "sqlusername";     
    $pwd "sqlpassword";   
    $databaseName "DBName";   
      
    $connectionInfo = array( "UID"=>$uid,                             
                             
    "PWD"=>$pwd,                             
                             
    "Database"=>$databaseName);   
        
    /* Connect using SQL Server Authentication. */   
    $conn sqlsrv_connect$serverName$connectionInfo);   
        
    $tsql "SELECT id, FirstName, LastName, Email FROM tblContact";   
        
    /* Execute the query. */   
        
    $stmt sqlsrv_query$conn$tsql);   
        
    if ( 
    $stmt )   
    {   
         echo 
    "Statement executed.<br>\n";   
    }     
    else     
    {   
         echo 
    "Error in statement execution.\n";   
         die( 
    print_rsqlsrv_errors(), true));   
    }   
        
    /* Iterate through the result set printing a row of data upon each iteration.*/   
        
    while( $row sqlsrv_fetch_array$stmtSQLSRV_FETCH_NUMERIC))   
    {   
         echo 
    "Col1: ".$row[0]."\n";   
         echo 
    "Col2: ".$row[1]."\n";   
         echo 
    "Col3: ".$row[2]."<br>\n";   
         echo 
    "-----------------<br>\n";   
    }   
        
    /* Free statement and connection resources. */   
    sqlsrv_free_stmt$stmt);   
    sqlsrv_close$conn);   
    ?>    
     
    Elshadriel likes this.
  3. That worked perfectly - thank you!
     
    Elshadriel and ComputerMan like this.

Share This Page