-1

I am using sqlsrv_connect in my connection php file. My connection is successful but will not allow me to use the query() function to start pulling data

My Connection file:

<?php
$serverName = "..."; 
$uid = "...";   
$pwd = "";  
$databaseName = "..."; 

try {
$connectionInfo = array( "UID"=>$uid,                            
                         "PWD"=>$pwd,                            
                         "Database"=>$databaseName); 

/* Connect using SQL Server Authentication. */  
$connectionInfo = sqlsrv_connect( $serverName, $connectionInfo); 

  echo "Connected successfully";
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}

?>

My Query:

<?php
    include_once 'includes/dataconn2.inc.php';
    $sql = "SELECT C_CODE, C_ID, C_DESCRIPTION FROM t_product";
    $result = $connectionInfo->query($sql);

?>

I've tried inputting the query directly, but it makes no difference.

Top-Master
  • 7,611
  • 5
  • 39
  • 71
SamATEIT
  • 9
  • 1
  • 3
  • 1
    https://www.php.net/manual/en/function.sqlsrv-query.php - `sqlsrv_query` is what you need. Unlike (for example) the mysqli library, this one has no object-oriented equivalent. – ADyson Dec 05 '22 at 12:38
  • ^Alternatively, if you do want to use an OOP aproach, you can use `PDO` if you install the correct drivers - See [here](https://stackoverflow.com/questions/12747554/connect-to-sql-server-through-pdo-using-sql-server-driver) – DarkBee Dec 05 '22 at 12:44
  • it now says "Fatal error: Uncaught Error: Call to a member function sqlsrv_query() on bool in C:\xampp\htdocs\BOMUpdaterTwo\testing.php:5 Stack trace: #0 {main} thrown in..." – SamATEIT Dec 05 '22 at 13:01
  • 1
    Then your connection to the server failed and `$connectionInfo` results to `false` – DarkBee Dec 05 '22 at 13:10
  • Again though, read the documentation **properly**. The correct syntax would be `sqlsrv_query($connectionInfo, $sql);`. Once again, there isn't an OO interface to this library – ADyson Dec 05 '22 at 13:31

1 Answers1

1

First of all, as you don't use PDO, fix your error handling by changing from:

try {
    // ...

    $connectionInfo = sqlsrv_connect($serverName, $connectionInfo);
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

Into:

// ...

$connectionInfo = sqlsrv_connect($serverName, $connectionInfo);
if ( ! $connectionInfo) {
    exit('Connection failed: '
        . print_r(sqlsrv_errors(), true)
    );
}

Finally, your query should be like:

$result = sqlsrv_query($connectionInfo, $sql);

Because unlike PDO and/or mysqli, sqlsrv has no object-oriented API.

Top-Master
  • 7,611
  • 5
  • 39
  • 71