Fur Fur - 7 months ago 25
PHP Question

PHP 'sqlsrv_query' null in resource

<?php

class Database {

protected $server;

function __construct($sql_server) {

$this->server = $sql_server;

}

public function connect() {

$connect = sqlsrv_connect($this->server, ["Database" => "ACCOUNT_DBF"]); // Windows Auth

if(!$connect) { die(print_r(sqlsrv_errors(), true)); }
else { echo "Connection established!"; }

}

public function userExists($data) {

$query = sqlsrv_query($his->server, "SELECT * FROM ACCOUNT_TBL where account = '$data'");

if(!$query) { die(print_r(sqlsrv_errors(), true)); }
else { echo "Bind success."; }

}

}

$db = new Database("YNCA\SQLEXPRESS");

$db->connect();
$db->userExists("bush");

?>


The $db->userExists("bush"); gives me a null resource in parameter, I cannot figure it out to why. Tho, I passed a valid parameter string into the $data in the userExists function.

EDIT : Fixed it with this final piece of code:

<?php

class Database {

protected $server, $connect;

function __construct($sql_server) {

$this->server = $sql_server;

}

public function connect() {

$this->connect = sqlsrv_connect($this->server, ["Database" => "ACCOUNT_DBF"]); // Windows Auth

if(!$this->connect) { die(print_r(sqlsrv_errors(), true)); }
else { echo "Connection established!"; }

}

public function userExists($data) {

$query = sqlsrv_query($this->connect, "SELECT * FROM ACCOUNT_TBL where account = ?", ["$data"]);

if(!$query) { die(print_r(sqlsrv_errors(), true)); }
else { echo "Bind success."; }

}

}

$db = new Database("YNCA\SQLEXPRESS");

$db->connect();
$db->userExists("bush");

?>

Answer

Store the connection resource into an object property and pass it to sqlsrv_query instead of $his->server. If passing the server string would be correct at this point, there is also a typo in $his->server ($this->server)

class Database {
  protected
    $server,
    $connection
  ;

// ...

public function connect() {
  $this->connection = sqlsrv_connect($this->server, ["Database" => "ACCOUNT_DBF"]); // Windows Auth
  // ...
}

public function userExists($data) {
  $query  = sqlsrv_query($his->connection, "SELECT * FROM ACCOUNT_TBL where account = '$data'");
  // ...
}