Search code examples
phpconnectiondatabase-connection

How do I remove the line "Connection established." from the PHP to SQL Server connection script?


I've made a connection between PHP and SQL Server using XAMPP with the code below:

koneksi.php

<?php
$serverName = "192.168.0.6"; //serverName\instanceName
$connectionInfo = array( "Database"=>"goldmart", "UID"=>"", "PWD"=>"");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Connection established.<br />";
}else{
     echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
}

// Close the connection.
sqlsrv_close( $conn );
?>

This is the result when I run the code above:
(https://i.sstatic.net/BcZDZ.jpg)

Then I display the data with the following code, but the message "Connection established." appear.

tes.php

<?php 
include "koneksi.php";
$conn = sqlsrv_connect($serverName, $connectionInfo);  
$sql = "SELECT * FROM dbo.mJenis";
$call=sqlsrv_query($conn, $sql);
if($call === false){
    die(print_r(sqlsrv_errors(), true));
}
while($row = sqlsrv_fetch_array($call, SQLSRV_FETCH_ASSOC)) {
    echo $row['kode'].", ".$row['Nama']."<br />";
}

sqlsrv_free_stmt( $call);
?>

(https://i.sstatic.net/Rxs3i.jpg)

The question is: how do I remove the message "Connection established."??

I've been browsing and can't find how to solve this problem. Please help. Thank you.


Solution

  • a) Only print the error in case the connection is not established:

    if( !$conn ) {
      echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
    }
    

    b) Also use sqlsrv_close( $conn ); in your other code file, not in the connection code file.

    c) remove $conn = sqlsrv_connect($serverName, $connectionInfo); from your other file as you already have the connection code included.

    So the code needs to be like this:

    Connection file (koneksi.php):

    <?php
        $serverName = "192.168.0.6";
        $connectionInfo = array( "Database"=>"goldmart", "UID"=>"", "PWD"=>"");
        $conn = sqlsrv_connect( $serverName, $connectionInfo);
        if( !$conn ) {
             echo "Connection could not be established.<br />";
             die( print_r( sqlsrv_errors(), true));
        }
    ?>
    

    Another file:

    <?php 
        include "koneksi.php";
        $sql = "SELECT * FROM dbo.mJenis";
        $call = sqlsrv_query($conn, $sql);
        if($call === false){
            die(print_r(sqlsrv_errors(), true));
        }
        while($row = sqlsrv_fetch_array($call, SQLSRV_FETCH_ASSOC)) {
            echo $row['kode'].", ".$row['Nama']."<br />";
        }
    
        sqlsrv_free_stmt( $call);
        // Close the connection.
        sqlsrv_close( $conn );
    ?>