PHP CodeIgniter Error: Undefined Property: Model - php

I was trying to use a inherited model, by creating a model in core/ folder, and create a newer model that extends the model in core/ folder, but then, when I try to log in, I get this error:
Severity: Notice
Message: Undefined property: CL_Login::$M_Login
Filename: controllers/CL_Login.php
Line Number: 47
The form is showed correctly, and posts to the following controller CL_Login/VerifyLogin.
I have created the following controller:
public function VerifyLogin()
{
$this->form_validation->set_rules('InputUsername', 'Username', 'required');
$this->form_validation->set_rules('InputPassword', 'Password', 'required|callback_CheckPassword');
if ($this->form_validation->run())
{
echo 'login sukses';
}
else
{
echo 'login gagal';
}
}
public function CheckPassword()
{
$output = $this->M_Login->get_login($this->input->post('InputUsername'),$this->input->post('InputPassword'));
print_r($output);
// if($output)
// {
// return true;
// }
// else
// {
// return false;
// }
}
And here's the model inside Model folder:
class M_Login extends MY_Model {
protected $table = 'ms_user';
protected $primary_key = 'user_id';
public function __construct()
{
parent::__construct();
}
public function get_login($query = NULL, $username, $password)
{
$query['where']['user_name'] = $username;
$query['where']['user_password'] = md5($password);
return $this->get($query);
}
}
And here's the model inside core folder:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Master model of SimplaCMS
*
* #author Akbar Syarif
* #email aksa.uncp#gmail.com
* #package SimplaCMS
*/
class MY_Model extends CI_Model {
// table
protected $table;
// primary key
protected $primary_key;
// error status
protected $error = FALSE;
// error message
protected $error_message = array();
public function __construct()
{
parent::__construct();
}
/**
* Add custom data to table
*
* #param Array (data)
* #return boolen. true if data successfully save and false if error occured
*/
public function insert( $data = NULL )
{
// if data not set
if ( is_null($data) ) {
$this->error = TRUE;
throw new Exception("The first parameter cannot be empty");
}
// if data not array
if ( ! is_array($data) ) {
$this->error = TRUE;
throw new Exception("The first parameter must be an array");
}
if ( ! $this->error ) {
$this->db->insert($this->table, $data);
} else {
return FALSE;
}
}
public function insert_batch( $data = NULL )
{
// if data not set
if ( is_null($data) ) {
$this->error = TRUE;
throw new Exception("The first parameter cannot be empty");
}
// if data not array
if ( ! is_array($data) ) {
$this->error = TRUE;
throw new Exception("The first parameter must be an array");
}
if ( ! $this->error ) {
$this->db->insert_batch($this->table, $data);
} else {
return FALSE;
}
}
/**
* Get row
* #param Array (data)
* #return mixed. return false if nothing row found,
* return object if there's at least one row found
*/
private function _get( $query = NULL )
{
if(isset($query['select'])) $this->db->select($query['select']);
if(isset($query['where'])) $this->db->where($query['where']);
if(isset($query['where_no_escaped'])) $this->db->where($query['where_no_escaped'], NULL, FALSE);
if(isset($query['or_where'])) $this->db->or_where($query['or_where']);
if(isset($query['or_where_no_escaped'])) $this->db->or_where($query['or_where_no_escaped'], NULL, FALSE);
if(isset($query['like'])) $this->db->like($query['like']);
if(isset($query['order_by'])) $this->db->order_by($query['order_by']);
if(isset($query['limit'])) $this->db->limit($query['limit']);
if(isset($query['limit_offset'])) $this->db->limit($query['limit_offset'][0], $query['limit_offset'][1]);
// join table
if(isset($query['join'])) {
if ( ! is_array($query['join']) ) {
$this->error = TRUE;
throw new Exception("Join value must be an array");
} else {
foreach ($query['join'] as $key => $value) {
$this->db->join($value[0], $value[1], $value[2]);
}
}
}
// return result
if ( ! $this->error ) {
$result = $this->db->get($this->table);
} else {
$result = FALSE;
}
return $result;
}
public function get( $query = NULL )
{
$result = $this->_get($query)->result();
return $result;
}
public function row( $query = NULL )
{
$result = $this->_get($query)->row();
return $result;
}
public function count( $query = NULL )
{
$result = $this->_get($query)->num_rows();
return $result;
}
/**
* Delete row by primary key
* #param int. Primary Key
* #return boolean. return true if row successfully delete
*/
public function delete( $primary_key = NULL )
{
// if primary key not set
if ( is_null($primary_key) ) {
$this->error = TRUE;
throw new Exception("First parameter cannot be empty.");
}
// if nothing error
if ( ! $this->error ) {
$this->db
->where($this->primary_key, $primary_key)
->delete($this->table);
} else {
return FALSE;
}
}
/**
* Update row by primary key
* #param array. Custom data
* #param int. Primary Key
* #return boolen. return true if row successfully update
*/
public function update( $data, $primary_key )
{
// if first argument not set or not an array
if ( func_num_args() == 0 ) {
$this->error = TRUE;
throw new Exception("First parameter cannot be empty");
} else {
if ( ! is_array($data) ) {
$this->error = TRUE;
throw new Exception("First parameter must be an array");
}
}
// if second parameter not set
if ( func_num_args() == 0 ) {
$this->error = TRUE;
throw new Exception("First parameter cannot be empty");
}
// if nothing error
if ( ! $this->error ) {
$this->db
->set($data)
->where($this->primary_key, $primary_key)
->update($this->table);
} else {
return FALSE;
}
}
}
/* End of file MY_Model.php */
/* Location: ./application/models/MY_Model.php */
The controller receives the value from the textbox smoothly with no problem. However, I got the mentioned error above. What else should I check?

You have to ensure that you are loading the model which you can do in the your controllers constructor or in the method itself that is using it, by using $this->load->model('m_login');
And refer to it as ...
public function CheckPassword()
{
$output = $this->m_Login->get_login($this->input->post('InputUsername'),$this->input->post('InputPassword'));
print_r($output);
// More code here
}
See how that flies for you!

Related

Codeigniter 4 while unlinking shows the error: Trying to access array offset on value of type null

Into my project in Codeigniter 4 I want to delete the record from database as well as I want to unlink the file present into that record but it gives me the error of
Trying to access array offset on value of type null
Till now I have tried this but its not working according to what do I want, below is my code
public function delete($id = null)
{
$model = new AbcModel();
try{
$id=$this->request->getPost('id');
$this->record = $model->where('id', $id)->first();
$image = $this->record['image'];
if(unlink('.'.$image)){
$model->where('id', $id)->delete();
echo "delete";
}
}
catch(\Exception $e){
echo $e->getMessage();
}
}
}
My Model
<?php namespace App\Models;
class AbcModel extends MyModel
{
protected $table = 'abc';
protected $primaryKey = 'id';
}
Into the database I have saved the file as /public/uploads/abcfolder/Tulips.jpg
I think you have problem with your delete query not with unlinking so you are getting the error of Trying to access array offset on value of type null. So I have rectified your codes try it once
$id=$this->request->getPost('id');
$model = new CurriculumModel();
$record = $model->find($id);
$image = $record['image'];
$file='.'.$image;
if(is_file($file))
{
unlink($file);
$model->delete($id);
echo 'delete';
}
This code does works for me, I am not sure whether it will work for you or not but give it a try.
so it like me
<?php namespace Modules\Common\Libraries;
use CodeIgniter\HTTP\Response;
class CustomFile
{
protected string $error;
public function __construct()
{
$this->error = '';
}
/**
* #return string
*/
public function getError(): string
{
return $this->error;
}
public function removeSingleFile( $path)
{
try {
if (file_exists($path)) {
unlink($path);
}
} catch (\Exception $e) {
$this->error = $e->getMessage();
}
}
}
in your ctl or service
/**
* edit function
* #method : DELETE with params ID
* #param $id
* #param $foreignKey
*/
public function delete($id)
{
$cfs = new CustomFile();
$model = new MyModel();
$deleteById = $model->where(['id' => $id])->findAll();
if (is_null($deleteById)) $this->httpException(lang('Shared.api.exist'), ResponseInterface::HTTP_NOT_FOUND);
$model->where(['id' => $id])->delete();
foreach ($deleteById as $path) {
$cfs->removeSingleFile(ROOTPATH . $path->path);
}
}

Passing array of Objects in php 7.3

Hi there still new to PHP and struggling with something really basic and it's frustrating me cause I can't see the error. I have read the PHP manual on passing array of objects.
class Customer{
public $companyId;
public $customerId;
public $name;
public function __construct($companyId,$customerId,$name)
{
$this->companyId = $companyId;
$this->customerId = $customerId;
$this->name = $name;
}
}
class CustomersDB
{
...
/**
* #return Customer[]
*/
public function getCustomers($search_str): array {
$resultObj = array();
$result = NULL;
try {
if (! $this->db) {
die('Database handle not defined') ;
}
if ($search_str && ! empty($search_str)) {
$result = $this->ListCustomers(Utils::COMPANY_ID, $search_str, $this->db);
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$_tmp = new Customer($row['CompanyID'],
$row['CustomerID'],
$row['CustomerName']);
// $resultObj.push($_tmp);
$resultObj[] = $_tmp;
}
}
} catch (Exception $e) {
// echo Utils::logMsgtoWeb($e->getTraceAsString());
} finally {
$result = NULL;
}
return $resultObj;
}
}
use Respect\Rest\Routable;
class Customers implements Routable {
/**
*
* Can pass in a partial string to search for a customer
* or pass in an ID for a specific match.
*/
public function get($searchStr){
// header('Content-type: application/json');
$result = $this->custdb.getCustomers($searchStr); // ERRORS HERE
if ($result && ! empty($result)) {
return json_encode( $result);
} else {
return NULL;
}
}
}
I get this error: PHP Recoverable fatal error: Object of class Scheduler\db\CustomersDB could not be converted to string in Customers.php.
Any help would be appreciated.

Array to string conversion error -Slim Twig-

Setup: I have a slim application and I pulled in Illuminate DB and Twig view.
if (!$validator->passed()) {
$errors = $validator->errors();
$users = User::all();
return $this->view($response, 'auth.login', compact('errors','users'));
}
Problem: When I run the above code, I am able to retrieve the users variable in my view, but the errors variable throws the following error.
Notice: Array to string conversion in /Users/davidchen/Documents/sites/slim.com/vendor/twig/twig/lib/Twig/Environment.php(378) : eval()'d code
on line
70 Array
The errors variable returns a multidimensional array, below you'll find the result that I get from print_r($errors).
Array (
[username] => Array (
[0] => username already exists
)
[password] => Array (
[0] => password must consist of at least 6 characters
)
)
Here are my related project files:
Twig Setup File (app.php)
$c = $app->getContainer();
$capsule = new \Illuminate\Database\Capsule\Manager;
$capsule->addConnection($config['config']['db']);
$capsule->setAsGlobal();
$capsule->bootEloquent();
$c['db'] = function($c) use ($capsule){
return $capsule;
};
$c['view'] = function($c){
$options['cache']=false;
$view = new \Slim\Views\Twig(__DIR__."/../views", $options);
$view->addExtension(new \Slim\Views\TwigExtension(
$c->router,
$c->request->getUri()
));
$view->getEnvironment()->addGlobal('flash', $c->flash);
return $view;
};
$c['flash'] = function($c){
return new Slim\Flash\Messages();
};
Validator Class
namespace App\Models\Auth;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Capsule\Manager as DB;
use Carbon\Carbon;
use DateTime;
class Validator extends Model
{
protected $field_name,
$data,
$errors = [];
/*
* Main validator
*/
public function __construct($request, $fields = []){
$data = $request->getParams();
$this->data = $data;
foreach ($fields as $field => $constraints) {
$this->field_name = $field;
if (isset($data[$field])) {
$field_value = $data[$field];
foreach (explode("|", $constraints) as $constraint) {
$obj = explode(":", $constraint);
$function_name = $obj[0];
if (isset($obj[1])) {
if(method_exists($this, $function_name))
{
$this->$function_name($obj[1],$field_value);
}
}
}
}else{
if (strpos($constraints, 'required') !== false) {
$validator->report($validator->field_name.' field is requried');
}
}
}
return $this;
}
/*
* Object Interface Methods
*/
private function report($message){
$this->errors[$this->field_name][]= $message;
}
public function errors(){
return $this->errors;
}
public function passed(){
if (!count($this->errors)) {
return true;
}
}
/*
* Validation Rules
*/
public function max($length,$value){
if (strlen($value)>$length) {
$this->report("{$this->field_name} must consist of less than {$length} characters");
}
}
public function min($length,$value){
if (strlen($value)<$length) {
$this->report("{$this->field_name} must consist of atleast {$length} characters");
}
}
public function distinct($tableName,$value){
if (DB::table($tableName)->where($this->field_name, $value)->exists()) {
$this->report("{$this->field_name} already exists");
}
}
public function date($format,$date){
if (!preg_match("/\d{4}-\d{2}-\d{2}\b/",$date)) {
$this->report("incorrect {$this->field_name} values");
}else{
$d = DateTime::createFromFormat($format, $date);
if ($d && $d->format($format) !== $date) {
$this->report("{$this->field_name} format should be {$format}");
}
}
}
public function match($matchField,$value){
if (isset($this->data[$matchField])) {
$valueTwo = $this->data[$matchField];
if ($value !== $valueTwo) {
$this->report("{$this->field_name} does not match {$matchField}");
}
}else{
$this->report("{$matchField} is required");
}
}
public function format($type,$value){
switch ($type) {
case 'noWhiteSpace':
if (preg_match("/\s/",$value)) {
$this->report("{$this->field_name} may not contain any spaces");
}break;
case 'alpha':
if (preg_match("/[^a-zA-Z]/",$value)) {
$this->report("{$this->field_name} may only contain letters");
}break;
case 'alphaNum':
if (preg_match("/[^a-zA-Z0-9]/",$value)) {
$this->report("{$this->field_name} may only contain letters");
}break;
case 'email':
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
$this->report("in correct {$this->field_name} format");
}break;
default:
# code...
break;
}
}
}
Base Controller
namespace App\Controllers;
/**
*
*/
class Controller
{
protected $c;
function __construct($container)
{
$this->c = $container;
}
public function view($response, $path,$variables = []){
$this->c->view->render($response, str_replace(".","/",$path).".twig", $variables);
}
public function pathFor($routeName,$data = []){
return $this->c->router->pathFor($routeName,$data);
}
}
Auth Controller
namespace App\Controllers\Auth;
use App\Models\User\User;
use App\Controllers\Controller;
use App\Models\Auth\Validator;
/**
*
*/
class AuthController extends Controller
{
public function getLogin($request, $response){
return $this->view($response, 'auth.login');
}
public function postLogin($request, $response){
$validator = new Validator($request,[
'username'=>'required|min:3|max:64|format:alphaNum|distinct:users',
'password'=>'required|min:6|max:64|',
]);
if (!$validator->passed()) {
$errors = $validator->errors();
$users = User::all();
return $this->view($response, 'auth.login', compact('errors','users'));
}
return $this->view($response, 'home.login');
}
}
login.twig file
login.twig file
Hope one of you can shed some light on this problem. I've been struggling with this all morning.
You could try to loop over each item in a sequence. For example, to display a list of users provided in a variable called users:
<h1>Members</h1>
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% endfor %}
</ul>
Read more

Joomla Comonent update data

I'm working on a Joomla 3 component. Currently I'm programming the backend. I'm having a form to add new data and it is working quite well. But when I want to update the data the component creates a new item instead of updating the existing.
I was searching for position which let Joomla know, that this is an update, but without success.
So my question: what is the information that makes Joomla updating the data?
My Code:
Table:ia.php
class mkTableia extends JTable
{
/**
* Constructor
*
* #param object Database connector object
*/
function __construct(&$db)
{
parent::__construct('#__tbl_ia', 'ID', $db);
}
}
Model: ia.php
class mkModelia extends JModelAdmin
{
public function getTable($type = 'ia', $prefix = 'mkTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
public function getForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm('com_mk.ia', 'ia',
array('control' => 'jform', 'load_data' => $loadData));
if (empty($form))
{
return false;
}
return $form;
}
protected function loadFormData()
{
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState('com_mk.edit.ia.data', array());
if (empty($data))
{
$data = $this->getItem();
}
return $data;
}
}
View:view.html.php
class mkViewia extends JViewLegacy
{
/**
* display method of Hello view
* #return void
*/
public function display($tpl = null)
{
// get the Data
$form = $this->get('Form');
$item = $this->get('Item');
// Check for errors.
if (count($errors = $this->get('Errors')))
{
JError::raiseError(500, implode('<br />', $errors));
return false;
}
// Assign the Data
$this->form = $form;
$this->item = $item;
// Set the toolbar
$this->addToolBar();
// Display the template
parent::display($tpl);
}
/**
* Setting the toolbar
*/
protected function addToolBar()
{
$input = JFactory::getApplication()->input;
$input->set('hidemainmenu', true);
$isNew = ($this->item->ID == 0);
JToolBarHelper::title($isNew ? JText::_('COM_MK_MANAGER_MK_NEW')
: JText::_('COM_MK_MANAGER_MK_EDIT'));
JToolBarHelper::save('IA.save');
JToolBarHelper::cancel('IA.cancel', $isNew ? 'JTOOLBAR_CANCEL'
: 'JTOOLBAR_CLOSE');
}
}

PHP - MySQL wrapper class advice

i am writing a MySQL wrapper class to:
a.) replace a current one
b.) make life easier in terms of custom functionality
c.) to learn and improve
I am looking on advice on how to improve my techniques and coding style, so i would appreciate any input you could provide.
DISCLAIMER:
I am aware there are other database abstraction methods such as PDO but i wanted to write my own for the above reasons
Thanks,
Lee
Test Call
#!/usr/bin/php
<?php
include('mysql.class.php');
$_mysql = new mysqli_ls( array( 'debug_log' => TRUE, 'query_log' => TRUE ) );
if ($_mysql->connect('host','user','password','db') === FALSE) print_r( $_mysql->get_error() );
else print "#1 connected\n";
if ($_mysql->set_database('auth_tracker_test') === FALSE) print_r( $_mysql->get_error() );
else print "#1 database changed\n";
/// Execute standard query
$sql = "SELECT * from user";
if ($_mysql->SQLQuery($sql) === TRUE) print "#1 SELECT Query worked\n";
else print print_r( $_mysql->get_error() );
#print_r($_mysql->getArray());
print_r($_mysql->getRow());
$_mysql->disconnect();
?>
<?php
class mysqli_ls
{
/**************************************************************************/
/* SETUP VARIABLES */
/**************************************************************************/
private $E_OK = TRUE;
private $E_ERROR = FALSE;
private $db_host;
private $db_user;
private $db_port;
private $db_name;
private $db_pass;
private $result;
private $link = FALSE;
private $errorArr = array();
private $config = array( // Location of exisiting
'config_load' => FALSE,
'config_path' => 'database.cfg.php',
// Record errors to a file
'debug_log' => FALSE,
'debug_log_path' => '/tmp/mysql.debug.log',
// Record queries to a file
'query_log' => FALSE,
'query_log_path' => '/tmp/mysql.debug.log' );
private $fh_debug = FALSE;
private $fh_query = FALSE;
private $fh_config = FALSE;
/**************************************************************************/
/* MAGIC FUNCTIONS */
/**************************************************************************/
public function __construct( $config = '' )
{
// Config vars
if ( !empty($config) && is_array($config) ) $this->set_config($config);
// Open file handles if logs are required
// Debug Log
if ($this->config['debug_log'] === TRUE)
{
if (! $this->fh_debug = fopen($this->config['debug_log_path'], 'a') )
{
$this->handle_error('#01A', 'could not open debug log');
return $this->E_ERROR;
}
}
// Query Log
if ($this->config['query_log'] === TRUE)
{
if (! $this->fh_query = fopen($this->config['query_log_path'], 'a') )
{
$this->handle_error('#01B', 'could not open query log');
return $this->E_ERROR;
}
}
// Check mysqli functions are available
if (!function_exists('mysqli_connect'))
{
$this->handle_error('#01C', 'mysqli not installed');
return $this->E_ERROR;
}
return $this->E_OK;
}
public function __deconstruct()
{
if ($this->link) $this->disconnect();
return $this->E_OK;
}
/**************************************************************************/
/* CONNECTION MANAGEMENT */
/**************************************************************************/
public function connect($db_host='', $db_user='', $db_pass='', $db_name, $db_port='3306')
{
if (empty($db_host) || empty($db_user) || empty($db_pass) || empty($db_name) || empty($db_port))
{
$this->handle_error('#02A', 'Missing connection variables');
return $this->E_ERROR;
}
$this->db_host = $db_host;
$this->db_user = $db_user;
$this->db_pass = $db_pass;
$this->db_name = $db_name;
$this->db_port = $db_port;
$this->link = #new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name, $this->db_port);
if (mysqli_connect_error($this->link))
{
$this->handle_error(mysqli_connect_errno($this->link), mysqli_connect_error($this->link));
return $this->E_ERROR;
}
return $this->E_OK;
}
public function disconnect()
{
if ($this->link)
{
if ($this->link->close() === TRUE) return $this->E_OK;
else
{
$this->handle_error($this->link->errno, $this->link->error);
return $this->E_ERROR;
}
}
$this->handle_error('#03A','no activate database connection');
return $this->E_ERROR;
}
public function connect_existing()
{
}
public function set_database($database)
{
if ( $this->link->select_db($database) === FALSE )
{
$this->handle_error($this->link->errno, $this->link->error);
return $this->E_ERROR;
}
$this->E_OK;
}
/**************************************************************************/
/* SQL INTERFACE */
/**************************************************************************/
public function insert()
{
}
public function update()
{
}
public function delete()
{
}
public function select()
{
}
public function query($sql)
{
// If the result set has cleaned up, do so before a new query
if ($this->result) $this->result->close();
// Record query
if ($this->config['query_log'] === TRUE) $this->write_log('query', $sql);
if ($result = $this->link->query($sql));
{
$this->result = $result;
return $this->E_OK;
}
// Clean up the result set
$result->close();
// Query failed, handle error
$this->handle_error($this->link->errno, $this->link->error);
return $this->E_ERROR;
}
/**************************************************************************/
/* RESULT FUNCTIONS */
/**************************************************************************/
public function getArray($type = 'assoc')
{
switch($type)
{
case 'num':
$type = MYSQLI_NUM;
break;
case 'assoc':
$type = MYSQLI_ASSOC;
break;
case 'both':
$type = MYSQLI_BOTH;
break;
default:
$this->handle_error('#12A','invalid field type. Options are include num, assoc, both');
return $this->E_ERROR;
break;
}
$resultArr = array();
while( $row = $this->result->fetch_array( $type ) )
{
$resultArr[] = $row;
}
return $resultArr;
}
public function getRow($type = 'assoc')
{
switch($type)
{
case 'num':
$type = MYSQLI_NUM;
break;
case 'assoc':
$type = MYSQLI_ASSOC;
break;
case 'both':
$type = MYSQLI_BOTH;
break;
default:
$this->handle_error('#13A','invalid field type. Options are include num, assoc, both');
return $this->E_ERROR;
break;
}
return $this->result->fetch_array( $type );
}
public function num_row()
{
return $this->result->num_rows;
}
public function insert_id()
{
return $this->link->insert_id;
}
public function affected_rows()
{
return $this->link->affected_rows;
}
/**************************************************************************/
/* LEGACY SUPPORT */
/**************************************************************************/
public function SQLQuery($sql='')
{
if (empty($sql))
{
$this->handle_error('#19A','missing query string');
return $this->E_ERROR;
}
// Check for a select statement
if ( preg_match("/^select/i",$sql) === 0)
{
$this->handle_error('#19A','incorrect query type, SELECT expected');
return $this->E_ERROR;
}
// Execute query
if ($this->query($sql) === $this->E_ERROR) return $this->E_ERROR;
// Return number of rows
return $this->num_row();
}
public function SQLModify($sql='')
{
if (empty($sql))
{
$this->handle_error('#19A','missing query string');
return $this->E_ERROR;
}
// Execute query
if ($this->query($sql) === $this->E_ERROR) return $this->E_ERROR;
// Return affected rows
$this->affected_rows();
}
public function numRow()
{
return $this->num_row();
}
/**************************************************************************/
/* LOGGING AND DEBUGGING */
/**************************************************************************/
private function write_log($type, $msg)
{
$msg = date('Y-m-d H:i:s') ."\t". $type ."\t". $msg ."\n";
switch($type)
{
case 'error':
fwrite($this->fh_debug, $msg);
break;
case 'query':
fwrite($this->fh_query, $msg);
break;
default:
return $this->E_ERROR;
break;
}
}
private function handle_error($errormsg, $errorno)
{
$this->errorArr[] = array( 'code' => $errorno,
'error' => $errormsg );
if ($this->config['debug_log'] === TRUE)
{
$msg = "($errorno) $errormsg";
$this->write_log('error', $msg);
}
return $this->E_OK;
}
public function get_error($type = 'string')
{
switch($string)
{
case 'string':
$error = end($this->errorArr);
return $error['error'] .' ('. $error['code'] .')';
break;
case 'array':
return end($this->errorArr);
break;
}
return false;
}
/**************************************************************************/
/* SET CONFIG VARS */
/**************************************************************************/
public function set_config($config)
{
foreach ($config as $key => &$value)
{
if ( ! isset($this->config[$key]) )
{
$this->handle_error('#19A','invalid field type');
return $this->E_ERROR;
}
$this->config[$key] = $value;
}
return $this->E_OK;
}
/**************************************************************************/
} // Class END
?>
I made one myself once and added another class named MySqlTable, which represented a table. I returned it in the __GET function, so you could call a table with
$sql->tablename->select();
Here's the code for the __get function:
function __GET($name)
{
return new MySqlTable($this, $name);
}
The class was like this:
class MySqlTable
{
private $table;
private $mySql;
function MySqlTable(&$oMySql, $sTable)
{
$this->mySql = $oMySql;
$this->table = $sTable;
}
function &select($sWhere = '')
{
if (empty($sWhere))
{
$data = $this->mySql->query("SELECT * FROM " . $this->table);
}
else
{
$data = $this->mySql->query("SELECT * FROM " . $this->table . " WHERE " . $sWhere);
}
return $this->mySql->resultToArray($data);
}
}
Currently, your mysqli_ls class contains the result of a query. This makes it impossible to do two queries and use the results of the first query after the second query ran.
A better way would be to let the SQLQuery() method return a result object, which contains the result handle and methods to retrieve rows from the result.

Categories