Problems calling class function in another class function - php

I am trying to build my own little framework.
Now I am having problems calling class functions into another class function.
Users.php code
class User extends Connection{
public function __construct(Connection $conn, Log $log){
parent::__construct($log);
$this->conn = $conn;
}
public function generatePassword(){
$length = 12;
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$password = '';
for ($i = 0; $i < $length; $i++) {
$password .= $characters[rand(0, strlen($characters) - 1)];
}
return $password;
}
public function generateToken(){
$token = md5(uniqid(mt_rand(), true));
return $token;
}
public function checkUsername($prefix, $username){
echo "test";
}
}
$user = new User($conn, $log);
$conn = new Connection($log);
connection.php code
<?php
class Connection{
private $log;
private $db;
public function __construct(Log $log){
$this->log = $log;
$this->createConnection();
}
public function createConnection(){
$dataConnection = $this->getConnection();
$host = $dataConnection['localhost'];
$dbname = $dataConnection['dbname'];
$user = $dataConnection['user'];
$pass = $dataConnection['pass'];
try{
$this->db = new PDO('mysql:host='.$host.';dbname='.$dbname.'',$user,$pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->log->insertLog("installer","Trying to connect to database");
} catch(PDOException $e){
$this->errorHandling($e->getCode());
}
}
public function errorHandling($error){
switch ($error){
case 2002:
$this->log->insertLog("installer","Installer error code 2002: Host unknown");
return ('Host unkown');
break;
case 1049:
$this->log->insertLog("installer","Installer error code 1049: Database does not exist");
return ('Database does not exist');
break;
case 1045:
$this->log->insertLog("installer","Installer error code 1045: Could not connect to database");
return ('Could nog connect to database');
break;
}
}
public function getConnection(){
$xml = simplexml_load_file("config/config.xml");
$dataConnection = array();
$dataConnection['localhost'] = $xml->host;
$dataConnection['dbname'] = $xml->dbname;
$dataConnection['user'] = $xml->user;
$dataConnection['pass'] = $xml->pass;
return $dataConnection;
}
public function query($sql){
try {
$this->db->exec($sql);
} catch(PDOException $e) {
$this->errorHandling($e->getCode());
}
}
public function select($sql){
try{
$result = $this->db->prepare($sql);
$result->execute();
return $result->fetchAll();
} catch(PDOException $e){
$this->errorHandling($e->getCode());
}
}
}
$conn = new Connection($log);
$log = new Log();
Log.php code
<?php
class Log{
public function createLog($file){
$date = date("dmY");
$location = 'var/log/'.$file.'-'.$date.'.log';
if (!file_exists($location)){
$file = fopen($location, 'w');
$message = "/** LOG FILE CREATED **/\n";
file_put_contents($location,$message, FILE_APPEND);
fclose($file);
}
return $location;
}
public function insertLog($file,$message){
$date = date("d-m-Y H:i:s", time());
$location = $this->createLog($file);
$message = $date." - ".$message."\n";
file_put_contents($location, $message, FILE_APPEND);
}
}
$log = new Log();
Now when I am trying to call the function checkUsername on user.php (will be used to check if the username already exists in db) I get the error:
Notice: Undefined variable: log in
/opt/www/decocka2/web/www.anthonydecock.be/core/conn/connection.php on
line 77
Catchable fatal error: Argument 1 passed to Connection::__construct()
must be an instance of Log, null given, called in
/opt/www/decocka2/web/www.anthonydecock.be/core/conn/connection.php on
line 77 and defined in
/opt/www/decocka2/web/www.anthonydecock.be/core/conn/connection.php on
line 7
What am I doing wrong?

Try to create the connection and the log object before the user object.

Related

i have sql custom execution method, but there are found error unbuffered query

i have a class which has custom query execution. Then it shown some error if after i execute that.
SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.
I have search out my problem answer but, almost of them recommend me to put $stmt->closeCursor() in my code, but i have done with it and still get error. The error shown is same with error above. Below is my DBClassification class. Please help me. Thanks :)
<?php
class DBClassification
{
public $db = null;
public $host = "localhost";
public $user = "root";
private $pass = "";
public $path = __DIR__ . "\\";
public $prefixFilename = "klasifikasi_";
public $dbexception = [];
public $stmt;
public function setHost($host){
$this->host = $host;
}
public function setUser($user){
$this->user = $user;
}
public function setPass($pass){
$this->pass = $pass;
}
public function setPath($path)
{
if (!is_dir($path)) die ("Directory \$path is not correct!\n$path");
$lastchar = substr($path, -1);
if ($lastchar != "/" && $lastchar != "\\") $path = $path . "/";
if (strpos($path, '/') !== false) $path = str_replace("/","\\",$path);
$this->path = $path . $this->host . "\\"; // setting path to the generated output file
}
public function setPrefixFilename($prefixFilename){
$this->prefixFilename = $prefixFilename;
}
public function setDBException($dbexception=[]){
$this->dbexception = $dbexception;
}
public function init($host,$user,$pass,$path,$prefixFilename,$dbexception=[])
{
if (!$dbexception) $dbexception = ["information_schema","mysql","performance_schema","phpmyadmin","sys"];
$this->setHost($host);
$this->setUser($user);
$this->setPass($pass);
$this->setPath($path);
$this->setPrefixFilename($prefixFilename);
$this->setDBException($dbexception);
$this->openConnection();
}
// Establishing Connection to mysql database on specified host
public function openConnection(){
try {
$db = new PDO("mysql:host=".$this->host, $this->user, $this->pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->db = $db;
return true;
} catch (PDOException $e) {
die("Error!: " . $e->getMessage());
}
return false;
}
public function run(){
try {
$databases = $this->stmtExec("SHOW DATABASES",true);
foreach($databases as $database): // execute each database
$dbname = $database['Database']; // database name
if(!in_array($dbname,$this->dbexception)): // prevent clasifying dbname which contain in dbexception
echo "USE $dbname\n";
$this->stmtExec("USE $dbname");
$tables = $this->stmtExec("SHOW TABLES",true);
endif; // if(!in_array($dbname,$dbexception)):
endforeach; // foreach($databases as $database):
} catch (Exception $e) {
echo "Something wrong, failed to clasify each database in host " . $this->host . "\n";
die("Error!: ".$e->getMessage());
}
}
public function stmtExec($sql,$fetch=false)
{
try {
$this->stmt = $this->db->prepare($sql);
if ($fetch) {
if ($this->stmt->execute()) $return = $this->stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
$return = $this->stmt->execute();
}
$this->stmt->closeCursor();
} catch (PDOException $e) {
$errormsg = "db Error: ". $this->stmt->queryString . PHP_EOL . $e->getMessage();
$queryFilename = $this->path . "error.txt";
file_put_contents($queryFilename, $errormsg);
print_r($errormsg);die();
}
return $return;
}
}
[ANSWERED]
I have found the solution from that, i have to delete false status in pdo attribute "PDO::ATTR_EMULATE_PREPARES". I think it become error because it will check query in prepare method. And query "use $dbname" is one which has no output and will give error if prepare check is on. Thats all my opinion.

Run time error in PHP Static Properties and Accessing Global Instance within a Class

I designed a PHP Class with a Static Properties and I get a blank page without any error log, Kindly assist me whats wrong in my PHP Code?
<?php
ini_set("display_startup_errors", 1);
ini_set("display_errors", 1);
error_reporting(-1);
class Response
{
public $Status;
public $Message;
function __construct() {
$this->Status = FALSE;
$this->Message = "";
}
}
$response = new Response();
class Connection
{
static private $server = "localhost"
static private $database = "Student";
static private $user = "ram";
static private $password = "ram12345!";
static public $link;
public static function Trigger() {
try
{
if (!isset(self::$link)) {
self::$link = mysql_connect("localhost", "bbminfoc_bbm", "Princess4BBM.>") or die("Couldn't make connection.");
if(!self::$link)
{
$response->Status = FALSE;
$response->Message = "Database Connection Failed !";
}
else
{
if(!mysql_select_db(self::$database, self::$link))
{
$response->Status = FALSE;
$response->Message = "Couldn't select database Main !";
}
}
}
}
catch(Exception $e) {
$response->Status = FALSE;
$response->Message = "Exception: " . $e->getMessage();
}
if(!$response->Status)
{
unset(self::$link);
}
}
}
if(!isset(Connection::link))
{
Connection::Trigger();
}
$outp = json_encode($response);
if(isset($outp))
{
echo($outp);
}
else
{
echo("No Data");
}
?>
Kindly assist me in this code, I don't know what I did wrong in the above pasted code because I can't able to see the log information in error_log file.
As #Yolo already mentioned in the comment, there's a semicolon missing in Connection::Trigger(); and at static private $server = "localhost". As this will cause a parse error the script will fail before executing and you won't see any errors.
To see those errors you will have to find the php.ini configuration file and set
display_errors = on. Also you should consider using an IDE with automatic code linting which will show you potential parse errors while typing the code.
As taken from this answer.
The completely fixed code looks like this:
<?php
ini_set("display_startup_errors", 1);
ini_set("display_errors", 1);
error_reporting(-1);
class Response
{
public $Status;
public $Message;
function __construct() {
$this->Status = FALSE;
$this->Message = "";
}
}
$response = new Response();
class Connection
{
static private $server = "localhost";
static private $database = "Student";
static private $user = "ram";
static private $password = "ram12345!";
static public $link = null;
public static function Trigger() {
global $response;
try
{
if (self::$link !== null) {
self::$link = mysql_connect("localhost", "bbminfoc_bbm", "Princess4BBM.>") or die("Couldn't make connection.");
if(!self::$link)
{
$response->Status = FALSE;
$response->Message = "Database Connection Failed !";
}
else
{
if(!mysql_select_db(self::$database, self::$link))
{
$response->Status = FALSE;
$response->Message = "Couldn't select database Main !";
}
}
}
}
catch(Exception $e) {
$response->Status = FALSE;
$response->Message = "Exception: " . $e->getMessage();
}
if(!$response->Status)
{
self::$link = null;
}
}
}
if(Connection::$link !== null)
{
Connection::Trigger();
}
$outp = json_encode($response);
if(isset($outp))
{
echo($outp);
}
else
{
echo("No Data");
}
?>
In static private $server = "localhost" you missed the last ;
Also, i'm getting this error:
Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead) in ... on line 61
So, change if(!isset(Connection::link)) to if (Connection::$link !== null)
That should solve your problem.
NOTE
Please do not use mysql_* extension. It's deprecated. If you want to continue using mysql, change to PDO or mysqli
U dont need to unset connection it will automatically be unset.. after class,
u missed semicolon after localhost, u didn't call response inside function trigger...
<?php
ini_set("display_startup_errors", 1);
ini_set("display_errors", 1);
error_reporting(-1);
class Response
{
public $Status;
public $Message;
function __construct() {
$this->Status = FALSE;
$this->Message = "";
}
}
$response = new Response();
class Connection
{
static private $server = "localhost";
static private $database = "listings";
static private $user = "root";
static private $password = "";
static public $link;
public static function Trigger() {
global $response;
try
{
if (!isset(self::$link)) {
self::$link = mysql_connect("localhost", "root", "") or die("Couldn't make connection.");
if(!self::$link)
{
$response->Status = FALSE;
$response->Message = "Database Connection Failed !";
}
else
{
if(!mysql_select_db(self::$database, self::$link))
{
$response->Status = FALSE;
$response->Message = "Couldn't select database Main !";
}
}
}
}
catch(Exception $e) {
$response->Status = FALSE;
$response->Message = "Exception: " . $e->getMessage();
}
}
}
if(!isset(Connection::$link))
{
Connection::Trigger();
}
$outp = json_encode($response);
if(isset($outp))
{
echo "hello";
echo($outp);
}
else
{
echo "hello";
echo("No Data");
}
Change this to:
if(!isset(Connection::link))
{
Connection::Trigger();
}
This:
if(!isset(Connection::$link))
{
Connection::Trigger();
}

Fixing max_user_connections in PHP class using PDO

I have been adapting an older abstraction layer to use PDO but I am running into user x has more than 'max_user_connections' active connections SQLSTATE[HY000] [1203] errors when looping through large sets. I have been reading on http://php.net/manual/en/pdo.connections.php but all of my attempts to unset the $dbh from within the loops result in errors from having ended the connection.
Base class looks like
class DB {
public $pdo;
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
public function __construct()
{
$this->connect();
}
private function connect()
{
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$this->pdo = new PDO("mysql:host=$this->host;dbname=$this->dbname;charset=utf8;", $this->user, $this->pass, $options);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function __sleep()
{
return array('dsn', 'username', 'password');
}
public function __wakeup()
{
$this->connect();
}
public function __destruct()
{
$this->connection = null;
$this->pdo = null;
unset($this->pdo);
}
// CRUD methods follow including
function retrieve($where, $groupBy='', $order_by='') {
$query = "SELECT * FROM `$this->table` $where $groupBy $order_by";
$q = $this->pdo->prepare($query);
$q->execute();
$result = $q->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE,get_class($this));
// was $result = $q->fetchAll(PDO::FETCH_CLASS,get_class($this));
$this->query_log($query);
$q = null;
if ($result == 'NULL') {
return false;
} else {
return $result;
}
} // retrieve()
And an example that has the errors would be
if (in_array($_GET['type'], $types)) {
$type = $_GET['type'];
$rsObj = new ReservedSlug;
if ($type == 'artist') {
$obj = new CalendarArtist;
$slugfield = 'urlSlug';
$namefield = 'name';
} else if ($type == 'event') {
$obj = new CalendarEvent;
$slugfield = 'urlSlug';
$namefield = 'name';
} else if ($type == 'location') {
$obj = new Location;
$slugfield = 'UrlSlug';
$namefield = 'LocationName1';
}
$needslug = $obj->retrieve("TRIM(`$namefield`) != '' AND (`$slugfield` = '' OR `$slugfield` IS NULL) LIMIT 0,400");
if ($needslug) {
foreach ($needslug as $ns) {
$testslug = slugify($ns->$namefield);
list($reserved) = $rsObj->retrieve("`slug` = '$testslug' AND `type` = '$type'");
if (!$reserved) {
list($test) = $obj->retrieve("`$slugfield` = '$testslug'");
if ($test) {
for ($i = 2; $i < 26; $i++) {
list($test) = $obj->retrieve("`$slugfield` = '$testslug-$i'");
if (!$test) {
$slug = $testslug . '-' . $i;
}
}
} else { // not found in table
$slug = $testslug;
}
} else { // was reserved
$slug = false;
}
echo $ns->$namefield . " gets $slug<p>";
} // foreach needslug
} // if needslug
} // type found in array
So I need to understand how to not create new connections when an active connection is available and how to properly __destruct() these child objects. Where am I going wrong?

DB class wont load

I'm trying to connect using a simle db class. For some reason it only print out
"Initiate DB class"
test.php
include 'db.class.php';
echo 'Initiate DB class';
$db = new DB();
echo 'DB class did load';
db.class.php
class DB extends mysqli {
private static $instance = null;
private function __construct () {
parent::init();
$host = 'localhost';
$user = 'root';
$pass = 'MY_PASS';
$dbse = 'MY_DB';
parent::real_connect($host, $user, $pass, $dbse);
if (0 !== $this->connect_errno):
die('MySQL Error: '. mysqli_connect_error());
//throw new Exception('MySQL Error: '. mysqli_connect_error());
endif;
}
public function fetch ($sql, $id = null, $one = false) {
$retval = array();
if ($res = $this->query($sql)):
$index = 0;
while ($rs = $res->fetch_assoc()):
if ($one):
$retval = $rs; break;
else:
$retval[$id ? $rs[$id] : $index++] = $rs;
endif;
endwhile;
$res->close();
endif;
return $retval;
}
}
I have tried to search my log files for error but they come out empty.
Ok got it,
In your call to db your calling new DB(); which mean you're trying to call the constructor of your DB class.
In your DB class it looks like you're trying to create a singleton, but something is missing normally there would be something to assign the instance the database connection, and something that asks the instance if it's empty create a new connection or if it's not use the same instance.
At the end of the day to make this work you can change your constructor to public.
Try this:
Db_class:
class Db_class{
/***********************CONNECT TO DB*********************/
public function db_connect(){
$user = '***';
$db = '***';
$password = '***';
$host = '***';
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
}
catch(PDOException $err) {
echo "Error: ".$err->getMessage()."<br/>";
die();
}
return $dbh;
}
/******************PREPARE AND EXECUTE SQL STATEMENTS*****/
public function query($statement){
$keyword = substr(strtoupper($statement), 0, strpos($statement, " "));
$dbh = $this->db_connect();
if($dbh){
try{
$sql = $dbh->prepare($statement);
$exe = $sql->execute();
}
catch(PDOException $err){
return $err->getMessage();
}
switch($keyword){
case "SELECT":
$result = array();
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
return $result;
break;
default:
return $exe;
break;
}
}
else{
return false;
}
}
Other PHP:
$db = new Db_class();
$sql = "SQL STATEMENT";
$result = $db->query($sql);
Your constructor is marked as private which means new DB will raise an error. I see you have a private property to store an instance, are you missing the singleton method to return a new object?

Update PHP class from mssql_ to sqlsrv_

We've just updated PHP on our server, for the most part everything is fine, but the mssql_ functions aren't supported any more unfortunately. I've tried to update our previous class:
$connection['server'] = 'server, port';
$connection['user'] = 'user';
$connection['pass'] = 'pass';
$connection['db'] = 'db';
class mssqlClass {
function connect($dbhost = NULL){
global $connection;
if(! ISSET ($dbconnect)){
$dbconnect = mssql_Connect($connection['server'], $connection['user'], $connection['pass'], true);
}
if(! $dbconnect){
return 'Failed to Connect to Host';
}else{
$select = mssql_select_db($connection['db'], $dbconnect);
if(! $select){
return 'Failed to select Database';
}else{
return $dbconnect;
}
}
}
function getData ($query){
$this->data_array = array();
$result = mssql_query($query);
while ($row = mssql_fetch_assoc($result)) {
$this->data_array[] = $row;
}
$m = $this->data_array;
return $m;
}
function query($query){
$result = mssql_query($query) or die("Query didn't work");
}
}
To be compliant with sqlsrv_, and whilst I can connect to the database without any issues, it won't return any data!:
class mssqlClass {
function connect($database = 'Db') {
$mssql_server = 'server';
$mssql_data = array("UID" => 'uid',
"PWD" => 'pwd',
"Database" => $database);
if(! ISSET ($dbconnect)){
$dbconnect = sqlsrv_connect($mssql_server, $mssql_data);
}
if(! $dbconnect){
return 'Failed to connect to host';
}
}
function getData ($query) {
$result = sqlsrv_query($db->connect, $query);
while ($row = sqlsrv_fetch_array($result)) {
$this->data_array[] = $row;
}
$m = $this->data_array;
return $m;
}
function query($query) {
$result = sqlsrv_query($query) or die("Query didn't work.");
}
}
ps. Example usage is as follows:
$db = new mssqlClass();
$conn = $db->connect('DATABASE');
$query = "SELECT * FROM Table";
$result= $db->getData($query);
So sorry for the horrible amount of code - I can edit it down to just the getData function if that's easier? Thank you!!
I've made some changes in your class:
<?php
class mssqlClass {
protected $connection = null;
public function connect($database = 'Db') {
// we don't need to connect twice
if ( $this->connection ) {
return;
}
// data for making connection
$mssql_server = 'gc-hr01';
$mssql_data = array("UID" => 'uid',
"PWD" => 'pwd',
"Database" => $database);
// try to connect
$this->connection = sqlsrv_connect($mssql_server, $mssql_data);
if(! $dbconnect){
return 'Failed to connect to host';
}
}
public function getData ($query) {
// reset results; is this really needed as object's variable? Can't it be just local function's variable??
$this->data_array = array();
$result = $this->query($this->connection, $query);
while ($row = sqlsrv_fetch_array($result)) {
$this->data_array[] = $row;
}
return $this->data_array;
}
public function query($query) {
$result = sqlsrv_query($query) or die("Query didn't work..");
}
}
The code looks fine. The only thing which could be your problem is that sqlsrv_fetch_array needs maybe a second parameter e.g.:
sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC)
Because the default is that it returns two arrays with different formats. And if you may acess attributes by name it will return nothing but not fail.
Something like this. Because you actually call the sqlsrv_query method with the return value of the following method. And in the original version you missed to return the connection resource.
function connect($database = 'Db') {
$mssql_server = 'gc-hr01';
$mssql_data = array("UID" => 'uid',
"PWD" => 'pwd',
"Database" => $database);
$dbconnect = sqlsrv_connect($mssql_server, $mssql_data);
if(! $dbconnect){
return 'Failed to connect to host';
}
return $dbconnect;
}
in advance
function getData ($query) {
$result = sqlsrv_query($db->connect(), $query);
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
$this->data_array[] = $row;
}
$m = $this->data_array;
return $m;
}
function query($query) {
$result = sqlsrv_query($query) or die("Query didn't work.");
}
I found this page while trying to find a quick short-cut to someone else's wrapper class for sqlsrv commands. Since this wasn't really complete, I have compiled my own quickly. Please don't think this is production code, you should test and test again, but it might help someone out of a jam quickly.
class db {
protected $connection = null;
private $debug = true;
private $stmt = null;
private $insertid = null;
private $affectedrows = null;
public function db($host = '.',$database,$username,$password) {
// we don't need to connect twice
if ( $this->connection ) {
return;
}
sqlsrv_configure('WarningsReturnAsErrors', 0);
// data for making connection
$sqlsvr_details = array( 'UID' => $username,
'PWD' => $password,
'Database' => $database,
'CharacterSet' => 'UTF-8'
);
// try to connect
$this->connection = sqlsrv_connect($host, $sqlsvr_details);
if($this->connection == false){
$this->debug('Failed to connect to host: '.$this->errors(),true);
return false;
}else{
return true;
}
}
public function query($query) {
return new resultset($query,$this->connection,$this->debug);
}
private function debug ($message,$hard = false){
if ($this->debug){
if ($hard){
die($message);
}else{
echo $message;
}
}
return true;
}
public function delete($query){
return $this->update($query);
}
public function update($query){
//Not happy with this
$this->affectedrows = null;
$this->insertid = null;
$this->stmt = sqlsrv_query($this->connection, $query);
if (!$this->stmt){
$this->debug('SQL Query Failed: '.$query.' '.$this->errors(),true);
return false;
}else{
$this->affectedrows = #sqlsrv_rows_affected($this->stmt);
return $this;
}
}
public function insert($query){
//Not happy with this
$this->affectedrows = null;
$this->insertid = null;
$this->stmt = sqlsrv_query($this->connection, $query);
if (!$this->stmt){
$this->debug('SQL Query Failed: '.$query.' '.$this->errors(),true);
return false;
}else{
//Get the last insert ID and store it on here
$this->insertid = $this->query('select ##IDENTITY as insert_id')->asObject()->insert_id;
return $this;
}
}
public function insert_id(){
return $this->insertid;
}
public function affected_rows(){
return $this->affectedrows;
}
private function errors(){
return print_r( sqlsrv_errors(SQLSRV_ERR_ERRORS), true);
}
}
class resultset implements Countable,Iterator {
private $result = null;
private $connection = null;
private $debug = false;
private $internal_pointer = 0;
private $data = array();
public function resultset($query,$link,$debug = false){
$this->connection = $link;
$this->debug = $debug;
$this->result = sqlsrv_query($this->connection, $query, array(), array('Scrollable' => SQLSRV_CURSOR_STATIC));
if ($this->result == false){
$this->debug('Query Failed: '.$query.' '.$this->errors(),true);
return false;
}else{
return $this;
}
}
public function asObject($step = true){
$object = sqlsrv_fetch_object($this->result,NULL,NULL,SQLSRV_SCROLL_ABSOLUTE,$this->internal_pointer);
if (! $object){
return false;
}else{
if ($step) $this->internal_pointer++;
return $object;
}
}
public function num_rows() {
return sqlsrv_num_rows($this->result);
}
public function free(){
$this->internal_pointer = 0;
if (is_resource($this->result)){
sqlsrv_free_stmt($this->result);
}
}
public function __destory(){
$this->free();
}
//Countable Function
public function count(){
return $this->num_rows();
}
//Iteration Functions
public function rewind(){
$this->internal_pointer = 0;
}
public function current(){
return $this->asObject(false);
}
public function key(){
return $this->internal_pointer;
}
public function next(){
$this->internal_pointer++;
}
public function valid(){
return $this->internal_pointer <= $this->num_rows();
}
//============================================
private function debug ($message,$hard = false){
if ($this->debug){
if ($hard){
die($message);
}else{
echo $message;
}
}
return true;
}
private function errors(){
return print_r( sqlsrv_errors(SQLSRV_ERR_ERRORS), true);
}
}

Categories