Skip to content

Instantly share code, notes, and snippets.

@mainIine
Last active August 18, 2021 12:24
Show Gist options
  • Save mainIine/2d682d3acc37b3825ca392060debf24e to your computer and use it in GitHub Desktop.
Save mainIine/2d682d3acc37b3825ca392060debf24e to your computer and use it in GitHub Desktop.
Tiny SqlSrv wrapper for Linux-PHP to connect and get data from a windows server
<?php
/*
* **************************************************************************************
*
* File: sqlsrv.php
* Author: Daniel Siekiera <[email protected]>
*
* Copyright © 2021
*
* **************************************************************************************
*
* Create connection
*
* $_sqlsrv = new sqlsrv([
* 'host' => HOST\PORT,
* 'user' => USER,
* 'password' => PASSWORD,
* 'db' => DBNAME,
* ]);
*
* $_sqlsrv->fetchCol for a single value
* or
* $_sqlsrv->fetchArray for all results in a array
*/
class sqlsrv
{
public $connection;
protected $statement = null;
protected $status = null;
function __construct($_con = '')
{
if (empty($_con))
{
exit('SqlSrv connection data missing!');
}
$connectionInfo = [
"UID" => $_con['user'],
"PWD" => $_con['password'],
"Database" => $_con['db']
];
$this->connection = sqlsrv_connect($_con['host'], $connectionInfo);
if ($this->connection)
{
$this->status = true;
}
else {
$this->status = false;
echo "Connection could not be established.<br />";
die( '<pre>' . print_r( sqlsrv_errors(), true));
}
}
/**
* Checks is the db connection is established. All queries for dynamic DB content should check is the
* connection is established and load fallback content if the connection value is false.
* @return bool
*/
public function getStatus(): ?bool
{
return $this->status;
}
/**
* Closes an open connection and releases resourses associated with the connection.
* @return bool true on success or false on failure.
*/
public function close(): bool
{
if ($this->connection) {
return sqlsrv_close($this->connection);
}
}
/**
* Prepared statement
* @param string $query sql query
* @return resource a statement resource on success and FALSE if an error occurred.
* @link http://www.php.net/manual/en/function.sqlsrv-prepare.php
*/
public function prepare(string $query)
{
return sqlsrv_prepare($this->connection, $query);
}
/**
* @param $preparedStatement
* @return bool true on success or false on failure
* @link http://www.php.net/manual/en/function.sqlsrv-execute.php
*/
public function execute($preparedStatement): bool
{
if (sqlsrv_execute($preparedStatement) === true) {
return true;
}
else {
return false;
}
}
/**
* @param $query string
* @return resource
*/
public function query(string $query)
{
$this->statement = sqlsrv_query($this->connection, $query);
if (!$this->statement) {
die(print_r(sqlsrv_errors(), true));
}
return $this->statement;
}
/**
* Return Last entered ID
* @return integer
*/
public function lastInsertId(): int
{
return (int)$this->fetchCol("SELECT SCOPE_IDENTITY() AS SCOPE_IDENTITY");
}
/**
* @return int
*/
public function getRowsAffected(): int
{
if (is_null($this->statement)) {
return -1;
}
$rowsAffected = sqlsrv_rows_affected($this->statement);
if ($rowsAffected == -1 || $rowsAffected === false) {
return -1;
}
return $rowsAffected;
}
/**
* @param $query string
* @return array of objects - Returns an object on success,
* NULL if there are no more rows to return,
* and FALSE if an error occurs or if the specified class does not exist.
* @link http://www.php.net/manual/en/function.sqlsrv-fetch-object.php
*/
public function fetchObject(string $query): array
{
$stmt = $this->query($query);
$a_array = [];
while ($res = sqlsrv_fetch_object($stmt))
{
$a_array[] = $res;
}
return $a_array;
}
/**
* @param string|null $query string
* @param int $type string - The type of array to return. SQLSRV_FETCH_ASSOC or
* SQLSRV_FETCH_NUMERIC
* for more info see here http://www.php.net/manual/en/function.sqlsrv-fetch-array.php
* @return array of array
*/
public function fetchArray(string $query = null, int $type = SQLSRV_FETCH_ASSOC): array
{
$stmt = $this->query($query);
$a_array = [];
while ($res = sqlsrv_fetch_array($stmt, $type))
{
$a_array[] = $res;
}
return $a_array;
}
/**
* @param $query string
* @return bool|string - Returns data from the specified field on success. Returns FALSE otherwise.
* @link http://www.php.net/manual/en/function.sqlsrv-get-field.php
*/
public function fetchCol(string $query)
{
$stmt = $this->query($query);
sqlsrv_fetch($stmt);
return sqlsrv_get_field($stmt, 0);
}
/**
* @param string $tableName - The name of the table. Returns all rows from the table requested.
* @param string $fields -
* @param int $type - The return type wanted. SQLSRV_FETCH_ASSOC
* OR SQLSRV_FETCH_NUMERIC
* @return bool|array - This method will return an associative or numeric array is results are returned.
* By default an associative array will be returned.
*/
public function get(string $tableName, string $fields = '*', int $type = SQLSRV_FETCH_ASSOC, $order = 'DESC')
{
if (is_array($fields))
{
$fieldsString = $this->fieldsBuilder($fields);
}
else {
$fieldsString = '*';
}
$sql = "SELECT $fieldsString FROM $tableName ORDER BY id $order";
$preparedStatement = sqlsrv_prepare($this->connection, $sql);
$result = sqlsrv_execute($preparedStatement);
$results = [];
if ($result === true)
{
if ($type == SQLSRV_FETCH_ASSOC)
{
while ($row = sqlsrv_fetch_array($preparedStatement, SQLSRV_FETCH_ASSOC)) {
$results[] = $row;
}
}
else {
while ($row = sqlsrv_fetch_array($preparedStatement, SQLSRV_FETCH_NUMERIC)) {
$results[] = $row;
}
}
return $results;
}
else {
return false;
}
}
/**
* Field builder
*
* @param $fields
* @return string
*/
public function fieldsBuilder($fields): string
{
$fieldsString = '';
$numberOfFeilds = count($fields);
$count = 1;
foreach ($fields as $value)
{
if ($count == $numberOfFeilds)
{
$fieldsString = $fieldsString . $value . ' ';
}
else {
$fieldsString = $fieldsString . $value . ' , ';
}
$count++;
}
return $fieldsString;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment