How to display fetched data of a database through a class function - php

I am new to OOP and want some help I have this some code that selects and fetches data from a database but I don't know how to display fetched data.
/**
* Connect to mysql database
*
* #return bool;
*/
public function Connect() {
$settings = database_settings();
$connect = new mysqli($settings->host, $settings->user, $settings->password, $settings->database);
if (!$connect->connect_errno) {
return $connect;
} else {
return false;
}
}
/**
* Prepare a mysqli query
*
* #return bool;
*/
public function statement($query) {
if (!empty($query)) {
$this->query = $query;
return true;
}
return false;
}
/**
* Execute a mysqli query and store result in memory
*
* #return bool;
*/
public function execute() {
$this->database = $this->Connect();
if (isset($this->query) && !empty($this->query)) {
$this->database->set_charset("utf8");
$this->exe = $this->database->query($this->query);
if (!isset($this->exe)) {
throw new DatabaseException("{$this->database->error} \n {$this->query} ");
}
if (isset($this->database->insert_id)) {
$this->last_id = $this->database->insert_id;
}
unset($this->query);
$this->database->close();
return true;
}
return false;
}
/**
* Prepare a query to select data from database
*
* #params = array();
* $params['from'] = names of table
* $params['params'] = names of columns which you want to select
* $params['wheres'] = specify a selection criteria to get required records
*
* #return bool;
*/
public function select($params, $multi = '') {
if (is_array($params)) {
if (!isset($params['params'])) {
$parameters = '*';
} else {
$parameters = implode(', ', $params['params']);
}
$order_by = '';
if (!empty($params['order_by'])) {
$order_by = "ORDER by {$params['order_by']}";
}
$where = '';
if (isset($params['wheres']) && is_array($params['wheres'])) {
$where = implode(' ', $params['wheres']);
}
$wheres = '';
if (!empty($params['wheres'])) {
$wheres = "WHERE({$where})";
}
$limit = '';
if (!empty($params['limit'])){
$limit = "LIMIT {$params['limit']}";
}
$query = "SELECT {$parameters} FROM `{$params['from']}` {$wheres} {$order_by} {$limit};";
$this->statement($query);
if ($this->execute()) {
return $this->fetch($multi);
}
}
return false;
}
/**
* Fetch the data from memory that is stored during execution;
*
* #params = $data = (ture if you want to fetch all data , or flase if only one row)
*
* #return bool;
*/
public function fetch($data = false) {
if (isset($this->exe)) {
if ($data !== true) {
if ($fetch = $this->exe) {
return arrayObject($fetch->fetch_assoc());
}
}
if ($data === true) {
if ($fetch = $this->exe) {
while ($all = $fetch->fetch_assoc()) {
$alldata[] = arrayObject($all);
}
}
if (isset($alldata) && !empty($alldata)) {
return arrayObject($alldata);
}
}
}
return false;
}
then i select data but can't display them:
$params['from'] = 'category';
$params['order_by']= 'id';
$params['wheres'] = 'active="1"';
$params['limit']= '1';
$connect->select($params);

Related

Getting uncaught refrence error in model.php file

I want to run a PHP website on localhost. I set up the server and imported the database but getting the following error...I Downloaded the website from the client c_panel public HTML folder and exported the database. I have to do changes in front-end and I have no idea of PHP(I am a Node.js developer, so if you can reference it with that to help me.). I just want to start the website locally, so that I can do the front-end changes. I'm getting the following error in my app/Models.php
Fatal error: Uncaught Error: Non-static method SB\Response::redirect() cannot be called statically in /Applications/MAMP/htdocs/app/src/sb/Model.php:475 Stack trace: #0 /Applications/MAMP/htdocs/app/src/sb/Model.php(12): SB\Model->db_error(Object(PDOException)) #1 /Applications/MAMP/htdocs/app/src/sb/DB.php(21): SB\Model->__construct() #2 /Applications/MAMP/htdocs/app/src/sb/DB.php(28): SB\DB->__construct() #3 /Applications/MAMP/htdocs/route/web.php(20): SB\DB::table('blogs') #4 /Applications/MAMP/htdocs/vendor/composer/autoload_real.php(66): require('/Applications/M...') #5 /Applications/MAMP/htdocs/vendor/composer/autoload_real.php(56): composerRequire6b60b5a5888bbd230d022934044bba82('8dab41e234cc925...', '/Applications/M...') #6 /Applications/MAMP/htdocs/vendor/autoload.php(7): ComposerAutoloaderInit6b60b5a5888bbd230d022934044bba82::getLoader() #7 /Applications/MAMP/htdocs/index.php(10): require_once('/Applications/M...') #8 {main} thrown in /Applications/MAMP/htdocs/app/src/sb/Model.php on line 475
Modal.php file:
<?php
namespace SB;
use PDO;
use PDOException;
class Model {
private $pdo = null;
public function __construct() {
try {
$this->pdo = new PDO(DSN, DB_USER, DB_PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
} catch (PDOException $e) {
$this->db_error($e);
}
}
/**
* Create table
* #param string $table A name of table to insert into
* #param string $data An associative array
*/
function create_table($table, $data) {
$sql = "CREATE TABLE IF NOT EXISTS $table (";
$num = count($data);
$sql .= "`_id` bigint(20) PRIMARY KEY NOT NULL AUTO_INCREMENT, ";
for ($i = 0; $i < $num; $i++):
$sql .= $data[$i] . ", ";
endfor;
$sql .= "`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, ";
$sql .="`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP);";
$this->pdo->exec($sql);
return '<big>This code was executed. Please check manually if no table is created for the database<big> <br> '.$sql ;
}
/**
* insert
* #param string $table A name of table to insert into
* #param string $data An associative array
*/
public function add($table, $data) {
ksort($data);
$this->pdo->beginTransaction();
$fieldNames = implode('`, `', array_keys($data));
$fieldValues = ':' . implode(', :', array_keys($data));
$sth = $this->pdo->prepare("INSERT INTO `$table` (`$fieldNames`) VALUES ($fieldValues)");
foreach ($data as $key => $value) {
$val = ltrim($value," ");
$sth->bindValue(":$key", $val);
}
$s = $sth->execute();
$this->pdo->commit();
return $s;
}
/**
* insert with get auto increment _id
* #param string $table A name of table to insert into
* #param string $data An associative array
*/
public function addGetId($table, $data) {
ksort($data);
$fieldNames = implode('`, `', array_keys($data));
$fieldValues = ':' . implode(', :', array_keys($data));
$sth = $this->pdo->prepare("INSERT INTO `$table` (`$fieldNames`) VALUES ($fieldValues)");
foreach ($data as $key => $value) {
$val = ltrim($value," ");
$sth->bindValue(":$key", $val);
}
$res = $sth->execute();
if($res) {
return $this->pdo->lastInsertId();
} else {
return $res;
}
}
/**
* update
* #param string $table A name of table to insert into
* #param string $data An associative array
* #param string $where the WHERE query part
*/
public function modify($table, $data,$where,$where_data = []) {
ksort($data);
$fieldDetails = NULL;
foreach ($data as $key => $value) {
$fieldDetails .= "`$key`=:$key,";
}
$fieldDetails = rtrim($fieldDetails, ',');
$sth = $this->pdo->prepare("UPDATE `$table` SET $fieldDetails $where");
foreach ($data as $key => $value) {
$val = ltrim($value," ");
$val = rtrim($val," ");
$sth->bindValue(":$key", $val);
}
foreach ($where_data as $key => $value) {
$sth->bindValue(":".$key, $value);
}
return $sth->execute();
}
/**
* Fetch all
* #param string $table A name of table to get all data
* #param string $cols the WHERE query part
* #param string $where the WHERE query part
* #param string $type the return data type
*/
public function fetch_all($table,$cols = '*',$where = false, $type = null,$where_data = []) {
$statement = '';
if(!$where) {
$statement = "SELECT $cols FROM $table";
} else {
$statement = "SELECT $cols FROM $table $where";
}
$pre = $this->pdo->prepare($statement);
$pre->execute($where_data);
if(gettype($type) == 'string') {
$type = strtoupper($type);
}
if(!$type || $type == 'NUM') {
return $pre->fetchAll(PDO::FETCH_NUM);
}
else if($type == 1 || $type == 'ASSOC') {
return $pre->fetchAll(PDO::FETCH_ASSOC);
} else {
return $pre->fetchAll(PDO::FETCH_OBJ);
}
}
/**
* Fetch one
* #param string $table A name of table to get all data
* #param string $cols the WHERE query part
* #param string $where the WHERE query part
* #param string $type the return data type
*/
public function fetch_one($table,$cols = '*',$where = false, $type = null,$where_data = []) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute($where_data);
if(gettype($type) == 'string') {
$type = strtoupper($type);
}
if(!$type || $type == 'NUM')
return $pre->fetch(PDO::FETCH_NUM);
else if($type == 1 || $type == 'ASSOC' )
return $pre->fetch(PDO::FETCH_ASSOC);
else
return $pre->fetch(PDO::FETCH_OBJ);
}
public function fetch_some($table, $cols, $where, $operator) {
ksort($where);
$fields = '';
$count = count($where);
$i = 0;
foreach($where as $key=>$val):
if($i<$count-1){
$fields .= $key.' '.$operator.' :'. $key.', ' ;
}else{
$fields .= $key.' '.$operator.' :'. $key;
} $i++;
endforeach;
$pre = $this->pdo->prepare("SELECT $cols FROM $table WHERE $fields");
foreach ($where as $key => $value):
$pre->bindValue(":$key", $value);
endforeach;
$pre->execute();
return $pre->fetch(PDO::FETCH_ASSOC);
}
/**
* Fetch row
* #param string $table A name of table to get all data
* #param string $cols the WHERE query part
*/
public function fetch_row($table, $cols = '*', $where = false, $operator = '=') {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
$pre->execute();
return $pre->fetch(PDO::FETCH_ASSOC);
}else{
if(!is_array($where)){
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
$pre->execute();
return $pre->fetch(PDO::FETCH_ASSOC);
} else {
return $this->pdo->fetch_some($table, $cols, $where, $operator);
}
}
}
/**
* Fetch rows
* #param string $table A name of table to get all data
* #param string $cols the WHERE query part
*/
public function fetch_rows($table, $cols = '*',$where = false) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute();
return $pre->fetchAll(PDO::FETCH_OBJ);
}
public function fetch_one_assoc($table,$cols = '*',$where = false) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute();
return $pre->fetch(PDO::FETCH_ASSOC);
}
public function fetch_one_object($table,$cols = '*',$where = false,$where_data = []) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
if(!empty($where_data))
$pre->execute($where_data);
else
$pre->execute();
return $pre->fetch(PDO::FETCH_OBJ);
}
public function fetch_all_assoc($table,$cols = '*',$where = false) {
if(!$where) {
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute();
return $pre->fetchAll(PDO::FETCH_ASSOC);
}
public function fetch_all_object($table,$cols = '*',$where = false) {
if(!$where){
$pre = $this->pdo->prepare("SELECT $cols FROM $table");
} else {
e = $this->pdo->prepare("SELECT $cols FROM $table $where");
}
$pre->execute();
return $pre->fetchAll(PDO::FETCH_OBJ);
}
/**
* Fetch type
* #param string $table A name of table to get all data
* #param string $where the WHERE query part
*/
public function fetch_type($table, $type = PDO::FETCH_OBJ, $limit = false,$cols = '*',$where = 1) {
$pre = $this->pdo->prepare("SELECT $cols FROM $table $where");
$pre->execute();
if(!$limit){
return $pre->fetchAll($type);
}else{
return $pre->fetch($type);
}
}
public function fetch_sql($sql,$type = PDO::FETCH_OBJ) {
$pre = $this->pdo->prepare($sql);
$pre->execute();
return $pre->fetchAll($type);
}
public function delete_row($table,$where,$operator = '=') {
ksort($where);
$fields = '';
$count = count($where);
$i = 0;
foreach($where as $key=>$val):
if($i<$count-1){
$fields .= $key.' '.$operator.' ? AND ' ;
} else {
$fields .= $key.' '.$operator.' ?';
} $i++;
endforeach;
$pre = $this->pdo->prepare("DELETE FROM $table WHERE $fields");
foreach ($where as $key => $value):
$a[] = $value;
endforeach;
return $pre->execute($a);
}
protected function deleteData($table,$where,$where_data=[]) {
$pre = $this->pdo->prepare("DELETE FROM $table $where");
foreach ($where_data as $key => $value) {
$pre->bindValue(":".$key, $value);
}
return $pre->execute();
}
public function customeDate($date=false) {
$date=date_create("$date");
return date_format($date,"dS-M-Y");
}
public function get_json($table) {
$rows = $this->pdo->fetch_all_assoc($table);
$out = "";
foreach($rows as $row) {
$cols = array_keys($row);
if ($out != "") {
$out .= ",";
}
foreach($cols as $i=>$col){
if($i==0){
$out .= '{"'.$col.'":"' . $row[$col] . '",';
} else {
$out .= '"'.$col.'":"' . $row[$col] . '",';
}
if($i==count($cols)-1) {
$out .= '"'.$col.'":"'. $row[$col] . '"}';
}
}
}
$out ='{"records":['.$out.']}';
return $out;
}
protected function connection_close() {
$this->pdo = null;
}
private function db_error($e) {
if(IS_DEBUGG):
die('
<br><h2><br>
<center>!Config Error.<br>
<small style="color:gray">Setup your .env file. Read Following Error</small>
</center></h2>
<h3>.env file variables</h3>
<ul>
<li>DB_HOST="Enter database host name"</li>
<li>DB_USER="Enter here database user name"</li>
<li>DB_PASS="enter Database Password"</li>
<li>DB_NAME="enter Database Name"</li>
<li>DB_DRIVER="DB DIRVER like `mysql`"</li>
</ul>
<br><div style="padding:50px;"><small style="color:lightgray"><pre>' . $e . '</pre></small></div>'
);
else:
return Response::redirect('404');
endif;
}
public function fetch_qry($sql,$one=0) {
$pre = $this->pdo->prepare($sql);
$pre->execute();
if($one)
return $pre->fetch(PDO::FETCH_ASSOC);
else
return $pre->fetchAll(PDO::FETCH_ASSOC);
}
}
Update this line of code
public static function redirect($endpoint){
#header('Location:'.URL.$endpoint);
}
Or, you can create an instance of this class.
$response = new Response();
Then call this method.
$response->redirect('404');

Receive only first line when using mysql SELECT

/**
* #param string $nick
* #return array|null
*/
public function getPlayerByNick(string $nick) : ?array{
$query = "SELECT * FROM reports";
$result = $this->connection->query($query);
if($result instanceof \mysqli_result){
$data = $result->fetch_assoc();
$result->free();
var_dump($data);
}
return null;
}
When I do var_dump I get only first user in the table, but I want to get them all. How can I do that?
Hopefully this your help
/**
* #param string $nick
* #return array|null
*/
public function getPlayerByNick(string $nick) : ?array{
$query = "SELECT * FROM reports";
$result = $this->connection->query($query);
if($result instanceof \mysqli_result){
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["nick"]);
}
}
return null;
}
/**
* #param string $nick
* #return array|null
*/
public function getPlayerByNick(string $nick) : ?array{
$query = "SELECT * FROM reports";
$result = $this->connection->query($query);
if($result instanceof \mysqli_result){
while($data = $result->fetch_assoc()){
var_dump($data);
}
$result->free();
}
return null;
}

Why I'm getting NULL on WHILE loop

I want get data from offers table ordered DESC by payout. If offer ID exist in offers_disabled_smart_link table, move to next and display link. What I'm doing wrong? I getting NULL when echo $link.
My DeliverService class is:
class DeliveryService {
protected $user_id;
protected $country;
protected $os;
protected $ip;
protected $referrer;
protected $token;
protected $smart_link;
public function __construct($user_id,$country,$ip,$os,$referrer,$token,$smart_link)
{
$this->user_id = $user_id;
$this->user_country = $country;
$this->user_ip = $ip;
$this->user_os = $os;
$this->user_referrer = $referrer;
$this->user_token = $token;
$this->smart_link_id = $smart_link;
}
public function getStatusOfferSmartLink($offer_id,$smart_link_id,$user_id)
{
global $db;
$sql="SELECT offer_id,smart_link_id,user_id FROM offers_disabled_smart_link WHERE smart_link_id=:smart_link_id AND offer_id=:offer_id and user_id=:user_id";
$stmp = $db->prepare($sql);
$stmp->execute(array(":smart_link_id"=>$smart_link_id,":offer_id"=>$offer_id,":user_id"=>$user_id));
$results = $stmp->fetchAll(PDO::FETCH_OBJ);
if($results)
return true;
else return false;
}
public function deliver()
{
global $db;
$sql="SELECT id, link, payout FROM offers ORDER BY payout DESC";
$stmp = $db->prepare($sql);
$stmp->execute();
while ($row = $stmp->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$link = $row['link'];
if($this->getStatusOfferSmartLink($id,$this->smart_link_id,$this->user_id)){
continue;
}
break;
$this->localFlag = true;
}
if ($this->localFlag) {
return $link;
}
}
Here I call function deliver() and echo $link
$ad = new DeliveryService(354,$country,$ip,$os,$referrer,$token,$smart_link);
$link = $ad->deliver();
echo $link;
If you want any informations, ask me.
Lets assume that your query return your expected data.
$this->localFlag = true; line will never execute as it's after break statement. (Assume that you didn't set $this->localFlag anywhere else.)
change this:
break;
$this->localFlag = true;
to:
$this->localFlag = true;
break;
and try. Hope it will work.

Class not found when include is working

I have these files:
/index.php
/Auth.class.php
/Config.class.php
/logcheck.php
/register.php
I am trying to include Auth.class.php and Config.class.php in register.php and logcheck.php, which is working fine like this:
include("Auth.class.php");
include("Config.class.php");
But when i'm trying to create an object of one of these classes in register.php i'm getting the Fatal Error: Class 'Config' not found in.... error message.
The imports are working but creating an object not. Config.class.php and Auth.class.php both belong to PHPAuth. I didn't use short tags. If you need any more information, just ask.
Edit:
register.php
<?php
include("languages/en_GB.php");
include("Config.class.php");
include("Auth.class.php");
$dbh = new PDO("mysql:host=localhost;dbname=phpauth", "root", "");
$config = new Config($dbh);
$auth = new Auth($dbh, $config, $lang);
$register = $auth->register($_POST['email'], $_POST['password'], $_POST['password']);
if($register['error']) {
// Something went wrong, display error message
echo '<div class="error">' . $register['message'] . '</div>';
} else {
// Logged in successfully, set cookie, display success message
/* setcookie($config->cookie_name, $login['hash'], $login['expire'], $config->cookie_path, $config->cookie_domain, $config->cookie_secure, $config->cookie_http);*/
echo '<div class="success">' . $login['message'] . '</div>';
}
?>
Config.class.php
<?php
namespace PHPAuth;
/**
* PHPAuth Config class
*/
class Config
{
private $dbh;
private $config;
private $config_table = 'config';
/**
*
* Config::__construct()
*
* #param \PDO $dbh
* #param string $config_table
*/
public function __construct(\PDO $dbh, $config_table = 'config')
{
$this->dbh = $dbh;
if (func_num_args() > 1)
$this->config_table = $config_table;
$this->config = array();
$query = $this->dbh->query("SELECT * FROM {$this->config_table}");
while($row = $query->fetch()) {
$this->config[$row['setting']] = $row['value'];
}
$this->setForgottenDefaults(); // Danger foreseen is half avoided.
}
/**
* Config::__get()
*
* #param mixed $setting
* #return string
*/
public function __get($setting)
{
return $this->config[$setting];
}
/**
* Config::__set()
*
* #param mixed $setting
* #param mixed $value
* #return bool
*/
public function __set($setting, $value)
{
$query = $this->dbh->prepare("UPDATE {$this->config_table} SET value = ? WHERE setting = ?");
if($query->execute(array($value, $setting))) {
$this->config[$setting] = $value;
return true;
}
return false;
}
/**
* Config::override()
*
* #param mixed $setting
* #param mixed $value
* #return bool
*/
public function override($setting, $value){
$this->config[$setting] = $value;
return true;
}
/**
* Danger foreseen is half avoided.
*
* Set default values.
* REQUIRED FOR USERS THAT DOES NOT UPDATE THEIR `config` TABLES.
*/
private function setForgottenDefaults()
{
// verify* values.
if (! isset($this->config['verify_password_min_length']) )
$this->config['verify_password_min_length'] = 3;
if (! isset($this->config['verify_password_max_length']) )
$this->config['verify_password_max_length'] = 150;
if (! isset($this->config['verify_password_strong_requirements']) )
$this->config['verify_password_strong_requirements'] = 1;
if (! isset($this->config['verify_email_min_length']) )
$this->config['verify_email_min_length'] = 5;
if (! isset($this->config['verify_email_max_length']) )
$this->config['verify_email_max_length'] = 100;
if (! isset($this->config['verify_email_use_banlist']) )
$this->config['verify_email_use_banlist'] = 1;
// emailmessage* values
if (! isset($this->config['emailmessage_suppress_activation']) )
$this->config['emailmessage_suppress_activation'] = 0;
if (! isset($this->config['emailmessage_suppress_reset']) )
$this->config['emailmessage_suppress_reset'] = 0;
}
}
Auth.class.php
<?php
namespace PHPAuth;
use ZxcvbnPhp\Zxcvbn;
use PHPMailer\PHPMailer\PHPMailer;
/***
* Auth class
* Required PHP 5.4 and above.
*/
class Auth
{
private $dbh;
public $config;
public $lang;
/***
* Initiates database connection
*/
public function __construct(\PDO $dbh, $config, $language = "en_GB")
{
$this->dbh = $dbh;
$this->config = $config;
if (version_compare(phpversion(), '5.4.0', '<')) {
die('PHP 5.4.0 required for PHPAuth engine!');
}
if (version_compare(phpversion(), '5.5.0', '<')) {
require("files/password.php");
}
// Load language
require "languages/{$language}.php";
$this->lang = $lang;
date_default_timezone_set($this->config->site_timezone);
}
/***
* Logs a user in
* #param string $email
* #param string $password
* #param int $remember
* #param string $captcha = NULL
* #return array $return
*/
public function login($email, $password, $remember = 0, $captcha = NULL)
{
$return['error'] = true;
$block_status = $this->isBlocked();
if($block_status == "verify")
{
if($this->checkCaptcha($captcha) == false)
{
$return['message'] = $this->lang["user_verify_failed"];
return $return;
}
}
if ($block_status == "block") {
$return['message'] = $this->lang["user_blocked"];
return $return;
}
$validateEmail = $this->validateEmail($email);
$validatePassword = $this->validatePassword($password);
if ($validateEmail['error'] == 1) {
$this->addAttempt();
$return['message'] = $this->lang["email_password_invalid"];
return $return;
} elseif($validatePassword['error'] == 1) {
$this->addAttempt();
$return['message'] = $this->lang["email_password_invalid"];
return $return;
} elseif($remember != 0 && $remember != 1) {
$this->addAttempt();
$return['message'] = $this->lang["remember_me_invalid"];
return $return;
}
$uid = $this->getUID(strtolower($email));
if(!$uid) {
$this->addAttempt();
$return['message'] = $this->lang["email_password_incorrect"];
return $return;
}
$user = $this->getBaseUser($uid);
if (!password_verify($password, $user['password'])) {
$this->addAttempt();
$return['message'] = $this->lang["email_password_incorrect"];
return $return;
}
if ($user['isactive'] != 1) {
$this->addAttempt();
$return['message'] = $this->lang["account_inactive"];
return $return;
}
$sessiondata = $this->addSession($user['uid'], $remember);
if($sessiondata == false) {
$return['message'] = $this->lang["system_error"] . " #01";
return $return;
}
$return['error'] = false;
$return['message'] = $this->lang["logged_in"];
$return['hash'] = $sessiondata['hash'];
$return['expire'] = $sessiondata['expiretime'];
return $return;
}
/***
* Creates a new user, adds them to database
* #param string $email
* #param string $password
* #param string $repeatpassword
* #param array $params
* #param string $captcha = NULL
* #param bool $sendmail = NULL
* #return array $return
*/
public function register($email, $password, $repeatpassword, $params = Array(), $captcha = NULL, $sendmail = NULL)
{
$return['error'] = true;
$block_status = $this->isBlocked();
if($block_status == "verify")
{
if($this->checkCaptcha($captcha) == false)
{
$return['message'] = $this->lang["user_verify_failed"];
return $return;
}
}
if ($block_status == "block") {
$return['message'] = $this->lang["user_blocked"];
return $return;
}
if ($password !== $repeatpassword) {
$return['message'] = $this->lang["password_nomatch"];
return $return;
}
// Validate email
$validateEmail = $this->validateEmail($email);
if ($validateEmail['error'] == 1) {
$return['message'] = $validateEmail['message'];
return $return;
}
// Validate password
$validatePassword = $this->validatePassword($password);
if ($validatePassword['error'] == 1) {
$return['message'] = $validatePassword['message'];
return $return;
}
$zxcvbn = new Zxcvbn();
if($zxcvbn->passwordStrength($password)['score'] < intval($this->config->password_min_score)) {
$return['message'] = $this->lang['password_weak'];
return $return;
}
if ($this->isEmailTaken($email)) {
$this->addAttempt();
$return['message'] = $this->lang["email_taken"];
return $return;
}
$addUser = $this->addUser($email, $password, $params, $sendmail);
if($addUser['error'] != 0) {
$return['message'] = $addUser['message'];
return $return;
}
$return['error'] = false;
$return['message'] = ($sendmail == true ? $this->lang["register_success"] : $this->lang['register_success_emailmessage_suppressed'] );
return $return;
}
/***
* Activates a user's account
* #param string $key
* #return array $return
*/
public function activate($key)
{
$return['error'] = true;
$block_status = $this->isBlocked();
if ($block_status == "block") {
$return['message'] = $this->lang["user_blocked"];
return $return;
}
if(strlen($key) !== 20) {
$this->addAttempt();
$return['message'] = $this->lang["activationkey_invalid"];
return $return;
}
$getRequest = $this->getRequest($key, "activation");
if($getRequest['error'] == 1) {
$return['message'] = $getRequest['message'];
return $return;
}
if($this->getBaseUser($getRequest['uid'])['isactive'] == 1) {
$this->addAttempt();
$this->deleteRequest($getRequest['id']);
$return['message'] = $this->lang["system_error"] . " #02";
return $return;
}
$query = $this->dbh->prepare("UPDATE {$this->config->table_users} SET isactive = ? WHERE id = ?");
$query->execute(array(1, $getRequest['uid']));
$this->deleteRequest($getRequest['id']);
$return['error'] = false;
$return['message'] = $this->lang["account_activated"];
return $return;
}
/***
* Creates a reset key for an email address and sends email
* #param string $email
* #return array $return
*/
public function requestReset($email, $sendmail = NULL)
{
$return['error'] = true;
$block_status = $this->isBlocked();
if ($block_status == "block") {
$return['message'] = $this->lang["user_blocked"];
return $return;
}
$validateEmail = $this->validateEmail($email);
if ($validateEmail['error'] == 1) {
$return['message'] = $this->lang["email_invalid"];
return $return;
}
$query = $this->dbh->prepare("SELECT id FROM {$this->config->table_users} WHERE email = ?");
$query->execute(array($email));
if ($query->rowCount() == 0) {
$this->addAttempt();
$return['message'] = $this->lang["email_incorrect"];
return $return;
}
$addRequest = $this->addRequest($query->fetch(\PDO::FETCH_ASSOC)['id'], $email, "reset", $sendmail);
if ($addRequest['error'] == 1) {
$this->addAttempt();
$return['message'] = $addRequest['message'];
return $return;
}
$return['error'] = false;
$return['message'] = ($sendmail == true ? $this->lang["reset_requested"] : $this->lang['reset_requested_emailmessage_suppressed']);
return $return;
}
/***
* Logs out the session, identified by hash
* #param string $hash
* #return boolean
*/
public function logout($hash)
{
if (strlen($hash) != 40) {
return false;
}
return $this->deleteSession($hash);
}
/***
* Hashes provided password with Bcrypt
* #param string $password
* #param string $password
* #return string
*/
public function getHash($password)
{
return password_hash($password, PASSWORD_BCRYPT, ['cost' => $this->config->bcrypt_cost]);
}
/***
* Gets UID for a given email address and returns an array
* #param string $email
* #return array $uid
*/
public function getUID($email)
{
$query = $this->dbh->prepare("SELECT id FROM {$this->config->table_users} WHERE email = ?");
$query->execute(array($email));
if($query->rowCount() == 0) {
return false;
}
return $query->fetch(\PDO::FETCH_ASSOC)['id'];
}
/***
* Creates a session for a specified user id
* #param int $uid
* #param boolean $remember
* #return array $data
*/
private function addSession($uid, $remember)
{
$ip = $this->getIp();
$user = $this->getBaseUser($uid);
if(!$user) {
return false;
}
$data['hash'] = sha1($this->config->site_key . microtime());
$agent = $_SERVER['HTTP_USER_AGENT'];
$this->deleteExistingSessions($uid);
if($remember == true) {
$data['expire'] = date("Y-m-d H:i:s", strtotime($this->config->cookie_remember));
$data['expiretime'] = strtotime($data['expire']);
} else {
$data['expire'] = date("Y-m-d H:i:s", strtotime($this->config->cookie_forget));
$data['expiretime'] = 0;
}
$data['cookie_crc'] = sha1($data['hash'] . $this->config->site_key);
$query = $this->dbh->prepare("INSERT INTO {$this->config->table_sessions} (uid, hash, expiredate, ip, agent, cookie_crc) VALUES (?, ?, ?, ?, ?, ?)");
if(!$query->execute(array($uid, $data['hash'], $data['expire'], $ip, $agent, $data['cookie_crc']))) {
return false;
}
$data['expire'] = strtotime($data['expire']);
return $data;
}
/***
* Removes all existing sessions for a given UID
* #param int $uid
* #return boolean
*/
private function deleteExistingSessions($uid)
{
$query = $this->dbh->prepare("DELETE FROM {$this->config->table_sessions} WHERE uid = ?");
$query->execute(array($uid));
return $query->rowCount() == 1;
}
/***
* Removes a session based on hash
* #param string $hash
* #return boolean
*/
private function deleteSession($hash)
{
$query = $this->dbh->prepare("DELETE FROM {$this->config->table_sessions} WHERE hash = ?");
$query->execute(array($hash));
return $query->rowCount() == 1;
}
/**
* Function to check if a session is valid
* #param string $hash
* #return boolean
*/
public function checkSession($hash)
{
$ip = $this->getIp();
$block_status = $this->isBlocked();
if ($block_status == "block") {
$return['message'] = $this->lang["user_blocked"];
return false;
}
if (strlen($hash) != 40) {
return false;
}
$query = $this->dbh->prepare("SELECT id, uid, expiredate, ip, agent, cookie_crc FROM {$this->config->table_sessions} WHERE hash = ?");
$query->execute(array($hash));
if ($query->rowCount() == 0) {
return false;
}
$row = $query->fetch(\PDO::FETCH_ASSOC);
$sid = $row['id'];
$uid = $row['uid'];
$expiredate = strtotime($row['expiredate']);
$currentdate = strtotime(date("Y-m-d H:i:s"));
$db_ip = $row['ip'];
$db_agent = $row['agent'];
$db_cookie = $row['cookie_crc'];
if ($currentdate > $expiredate) {
$this->deleteExistingSessions($uid);
return false;
}
if ($ip != $db_ip) {
return false;
}
if ($db_cookie == sha1($hash . $this->config->site_key)) {
return true;
}
return false;
}
/**
* Retrieves the UID associated with a given session hash
* #param string $hash
* #return int $uid
*/
public function getSessionUID($hash)
{
$query = $this->dbh->prepare("SELECT uid FROM {$this->config->table_sessions} WHERE hash = ?");
$query->execute(array($hash));
if ($query->rowCount() == 0) {
return false;
}
return $query->fetch(\PDO::FETCH_ASSOC)['uid'];
}
/**
* Checks if an email is already in use
* #param string $email
* #return boolean
*/
public function isEmailTaken($email)
{
$query = $this->dbh->prepare("SELECT count(*) FROM {$this->config->table_users} WHERE email = ?");
$query->execute(array($email));
if ($query->fetchColumn() == 0) {
return false;
}
return true;
}
/**
* Adds a new user to database
* #param string $email -- email
* #param string $password -- password
* #param array $params -- additional params
* #return int $uid
*/
private function addUser($email, $password, $params = array(), &$sendmail)
{
$return['error'] = true;
$query = $this->dbh->prepare("INSERT INTO {$this->config->table_users} VALUES ()");
if(!$query->execute()) {
$return['message'] = $this->lang["system_error"] . " #03";
return $return;
}
$uid = $this->dbh->lastInsertId();
$email = htmlentities(strtolower($email));
if($sendmail) {
$addRequest = $this->addRequest($uid, $email, "activation", $sendmail);
if($addRequest['error'] == 1) {
$query = $this->dbh->prepare("DELETE FROM {$this->config->table_users} WHERE id = ?");
$query->execute(array($uid));
$return['message'] = $addRequest['message'];
return $return;
}
$isactive = 0;
} else {
$isactive = 1;
}
$password = $this->getHash($password);
if (is_array($params)&& count($params) > 0) {
$customParamsQueryArray = Array();
foreach($params as $paramKey => $paramValue) {
$customParamsQueryArray[] = array('value' => $paramKey . ' = ?');
}
$setParams = ', ' . implode(', ', array_map(function ($entry) {
return $entry['value'];
}, $customParamsQueryArray));
} else { $setParams = ''; }
$query = $this->dbh->prepare("UPDATE {$this->config->table_users} SET email = ?, password = ?, isactive = ? {$setParams} WHERE id = ?");
$bindParams = array_values(array_merge(array($email, $password, $isactive), $params, array($uid)));
if(!$query->execute($bindParams)) {
$query = $this->dbh->prepare("DELETE FROM {$this->config->table_users} WHERE id = ?");
$query->execute(array($uid));
$return['message'] = $this->lang["system_error"] . " #04";
return $return;
}
$return['error'] = false;
return $return;
}
/**
* Gets basic user data for a given UID and returns an array
* #param int $uid
* #return array $data
*/
private function getBaseUser($uid)
{
$query = $this->dbh->prepare("SELECT email, password, isactive FROM {$this->config->table_users} WHERE id = ?");
$query->execute(array($uid));
if ($query->rowCount() == 0) {
return false;
}
$data = $query->fetch(\PDO::FETCH_ASSOC);
if (!$data) {
return false;
}
$data['uid'] = $uid;
return $data;
}
/**
* Gets public user data for a given UID and returns an array, password is not returned
* #param int $uid
* #return array $data
*/
public function getUser($uid)
{
$query = $this->dbh->prepare("SELECT * FROM {$this->config->table_users} WHERE id = ?");
$query->execute(array($uid));
if ($query->rowCount() == 0) {
return false;
}
$data = $query->fetch(\PDO::FETCH_ASSOC);
if (!$data) {
return false;
}
$data['uid'] = $uid;
unset($data['password']);
return $data;
}
/**
* Allows a user to delete their account
* #param int $uid
* #param string $password
* #param string $captcha = NULL
* #return array $return
*/
public function deleteUser($uid, $password, $captcha = NULL)
{
$return['error'] = true;
$block_status = $this->isBlocked();
if($block_status == "verify")
{
if($this->checkCaptcha($captcha) == false)
{
$return['message'] = $this->lang["user_verify_failed"];
return $return;
}
}
if ($block_status == "block") {
$return['message'] = $this->lang["user_blocked"];
return $return;
}
$validatePassword = $this->validatePassword($password);
if($validatePassword['error'] == 1) {
$this->addAttempt();
$return['message'] = $validatePassword['message'];
return $return;
}
$user = $this->getBaseUser($uid);
if(!password_verify($password, $user['password'])) {
$this->addAttempt();
$return['message'] = $this->lang["password_incorrect"];
return $return;
}
$query = $this->dbh->prepare("DELETE FROM {$this->config->table_users} WHERE id = ?");
if(!$query->execute(array($uid))) {
$return['message'] = $this->lang["system_error"] . " #05";
return $return;
}
$query = $this->dbh->prepare("DELETE FROM {$this->config->table_sessions} WHERE uid = ?");
if(!$query->execute(array($uid))) {
$return['message'] = $this->lang["system_error"] . " #06";
return $return;
}
$query = $this->dbh->prepare("DELETE FROM {$this->config->table_requests} WHERE uid = ?");
if(!$query->execute(array($uid))) {
$return['message'] = $this->lang["system_error"] . " #07";
return $return;
}
$return['error'] = false;
$return['message'] = $this->lang["account_deleted"];
return $return;
}
/**
* Creates an activation entry and sends email to user
* #param int $uid
* #param string $email
* #param string $type
* #param boolean $sendmail = NULL
* #return boolean
*/
private function addRequest($uid, $email, $type, &$sendmail)
{
$return['error'] = true;
if($type != "activation" && $type != "reset") {
$return['message'] = $this->lang["system_error"] . " #08";
return $return;
}
// if not set manually, check config data
if($sendmail === NULL)
{
$sendmail = true;
if($type == "reset" && $this->config->emailmessage_suppress_reset === true ) {
$sendmail = false;
$return['error'] = false;
return $return;
}
if ($type == "activation" && $this->config->emailmessage_suppress_activation === true ) {
$sendmail = false;
$return['error'] = false;
return $return;
}
}
$query = $this->dbh->prepare("SELECT id, expire FROM {$this->config->table_requests} WHERE uid = ? AND type = ?");
$query->execute(array($uid, $type));
if($query->rowCount() > 0) {
$row = $query->fetch(\PDO::FETCH_ASSOC);
$expiredate = strtotime($row['expire']);
$currentdate = strtotime(date("Y-m-d H:i:s"));
if ($currentdate < $expiredate) {
$return['message'] = $this->lang["reset_exists"];
return $return;
}
$this->deleteRequest($row['id']);
}
if($type == "activation" && $this->getBaseUser($uid)['isactive'] == 1) {
$return['message'] = $this->lang["already_activated"];
return $return;
}
$key = $this->getRandomKey(20);
$expire = date("Y-m-d H:i:s", strtotime($this->config->request_key_expiration));
$query = $this->dbh->prepare("INSERT INTO {$this->config->table_requests} (uid, rkey, expire, type) VALUES (?, ?, ?, ?)");
if(!$query->execute(array($uid, $key, $expire, $type))) {
$return['message'] = $this->lang["system_error"] . " #09";
return $return;
}
$request_id = $this->dbh->lastInsertId();
if($sendmail === true)
{
// Check configuration for SMTP parameters
$mail = new PHPMailer;
if($this->config->smtp) {
$mail->isSMTP();
$mail->Host = $this->config->smtp_host;
$mail->SMTPAuth = $this->config->smtp_auth;
if(!is_null($this->config->smtp_auth)) {
$mail->Username = $this->config->smtp_username;
$mail->Password = $this->config->smtp_password;
}
$mail->Port = $this->config->smtp_port;
if(!is_null($this->config->smtp_security)) {
$mail->SMTPSecure = $this->config->smtp_security;
}
}
$mail->From = $this->config->site_email;
$mail->FromName = $this->config->site_name;
$mail->addAddress($email);
$mail->isHTML(true);
if($type == "activation") {
$mail->Subject = sprintf($this->lang['email_activation_subject'], $this->config->site_name);
$mail->Body = sprintf($this->lang['email_activation_body'], $this->config->site_url, $this->config->site_activation_page, $key);
$mail->AltBody = sprintf($this->lang['email_activation_altbody'], $this->config->site_url, $this->config->site_activation_page, $key);
}
else {
$mail->Subject = sprintf($this->lang['email_reset_subject'], $this->config->site_name);
$mail->Body = sprintf($this->lang['email_reset_body'], $this->config->site_url, $this->config->site_password_reset_page, $key);
$mail->AltBody = sprintf($this->lang['email_reset_altbody'], $this->config->site_url, $this->config->site_password_reset_page, $key);
}
if(!$mail->send()) {
$this->deleteRequest($request_id);
$return['message'] = $this->lang["system_error"] . " #10";
return $return;
}
}
$return['error'] = false;
return $return;
}
/**
* Returns request data if key is valid
* #param string $key
* #param string $type
* #return array $return
*/
public function getRequest($key, $type)
{
$return['error'] = true;
$query = $this->dbh->prepare("SELECT id, uid, expire FROM {$this->config->table_requests} WHERE rkey = ? AND type = ?");
$query->execute(array($key, $type));
if ($query->rowCount() === 0) {
$this->addAttempt();
$return['message'] = $this->lang[$type."key_incorrect"];
return $return;
}
$row = $query->fetch();
$expiredate = strtotime($row['expire']);
$currentdate = strtotime(date("Y-m-d H:i:s"));
if ($currentdate > $expiredate) {
$this->addAttempt();
$this->deleteRequest($row['id']);
$return['message'] = $this->lang[$type."key_expired"];
return $return;
}
$return['error'] = false;
$return['id'] = $row['id'];
$return['uid'] = $row['uid'];
return $return;
}
/**
* Deletes request from database
* #param int $id
* #return boolean
*/
private function deleteRequest($id)
{
$query = $this->dbh->prepare("DELETE FROM {$this->config->table_requests} WHERE id = ?");
return $query->execute(array($id));
}
/**
* Verifies that a password is valid and respects security requirements
* #param string $password
* #return array $return
*/
File goes on but Character-Limitation is reached, I also don't think that the main code itself is necessary.
As pointed out by #Jeff in the comments, you have a namespace problem in register.php,
You can do one of the following,
Use use :
If you would use use your register.php would look like:
<?php
include("languages/en_GB.php");
include("Config.class.php");
include("Auth.class.php");
use \PHPAuth\{Config, Auth};
$dbh = new \PDO("mysql:host=localhost;dbname=phpauth", "root", "");
$config = new Config($dbh);
$auth = new Auth($dbh, $config, $lang);
$register = $auth->register($_POST['email'], $_POST['password'], $_POST['password']);
if($register['error']) {
// Something went wrong, display error message
echo '<div class="error">' . $register['message'] . '</div>';
} else {
// Logged in successfully, set cookie, display success message
/* setcookie($config->cookie_name, $login['hash'], $login['expire'], $config->cookie_path, $config->cookie_domain, $config->cookie_secure, $config->cookie_http);*/
echo '<div class="success">' . $login['message'] . '</div>';
}
?>
Or explicit declaration of the namespace when creating the object (that is using the FQN):
Then your register.php would look like:
<?php
include("languages/en_GB.php");
include("Config.class.php");
include("Auth.class.php");
$dbh = new PDO("mysql:host=localhost;dbname=phpauth", "root", "");
$config = new \PHPAuth\Config($dbh);
$auth = new \PHPAuth\Auth($dbh, $config, $lang);
$register = $auth->register($_POST['email'], $_POST['password'], $_POST['password']);
if($register['error']) {
// Something went wrong, display error message
echo '<div class="error">' . $register['message'] . '</div>';
} else {
// Logged in successfully, set cookie, display success message
/* setcookie($config->cookie_name, $login['hash'], $login['expire'], $config->cookie_path, $config->cookie_domain, $config->cookie_secure, $config->cookie_http);*/
echo '<div class="success">' . $login['message'] . '</div>';
}
?>
Hope it helps you!
Suggested Reading:
http://php.net/manual/en/language.namespaces.basics.php
http://php.net/manual/en/language.namespaces.rationale.php
http://php.net/manual/en/language.namespaces.php
Another thing: The use portion I have used in the first example is only compatible with PHP7. If you are using PHP lower than Version 7, then you can use this use declarations:
use \PHPAuth\Config;
use \PHPAuth\Auth;

How to write helper class for different select operation?

Guys i want different "select" operation as per my needs, but i just need one helper function for all select operation , How do i get it??
This is my helper class Database.php
<?php
class Database
{
public $server = "localhost";
public $user = "root";
public $password = "";
public $database_name = "employee_application";
public $table_name = "";
public $database_connection = "";
public $class_name = "Database";
public $function_name = "";
//constructor
public function __construct(){
//establishes connection to database
$this->database_connection = new mysqli($this->server, $this->user, $this->password, $this->database_name);
if($this->database_connection->connect_error)
die ("Connection failed".$this->database_connection->connect_error);
}
//destructor
public function __destruct(){
//closes database connection
if(mysqli_close($this->database_connection))
{
$this->database_connection = null;
}
else
echo "couldn't close";
}
public function run_query($sql_query)
{
$this->function_name = "run_query";
try{
if($this->database_connection){
$output = $this->database_connection->query($sql_query);
if($output){
$result["status"] = 1;
$result["array"] = $output;
}
else{
$result["status"] = 0;
$result["message"] = "Syntax error in query";
}
}
else{
throw new Exception ("Database connection error");
}
}
catch (Exception $error){
$result["status"] = 0;
$result["message"] = $error->getMessage();
$this->error_table($this->class_name, $this->function_name, "connection error", date('Y-m-d H:i:s'));
}
return $result;
}
public function get_table($start_from, $per_page){
$this->function_name = "get_table";
$sql_query = "select * from $this->table_name LIMIT $start_from, $per_page";
return $this->run_query($sql_query);
}
}
?>
In the above code get_table function performs basic select operation....
Now i want get_table function to perform all this below operations,
$sql_query = "select e.id, e.employee_name, e.salary, dept.department_name, desi.designation_name, e.department, e.designation
from employees e
LEFT OUTER JOIN designations desi ON e.designation = desi.id
LEFT OUTER JOIN departments dept ON e.department = dept.id
ORDER BY e.employee_name
LIMIT $start_from, $per_page";
$sql_query = "select id, designation_name from designations ORDER BY designation_name";
$sql_query = "select * from departments";
$sql_query = "select * from departments Limit 15,10";
So how to overcome this issue, can anyone help me out?
If you expand your class a bit, you could achieve what you are looking for. Something like this:
<?php
class Database
{
public $sql;
public $bind;
public $statement;
public $table_name;
protected $orderby;
protected $set_limit;
protected $function_name;
protected $sql_where;
protected $i;
protected function reset_class()
{
// reset variables
$this->sql = array();
$this->function_name = false;
$this->table_name = false;
$this->statement = false;
$this->sql_where = false;
$this->bind = array();
$this->orderby = false;
$this->set_limit = false;
}
protected function run_query($statement)
{
echo (isset($statement) && !empty($statement))? $statement:"";
}
public function get_table($start_from = false, $per_page = false)
{
// Compile the sql into a statement
$this->execute();
// Set the function if not already set
$this->function_name = (!isset($this->function_name) || isset($this->function_name) && $this->function_name == false)? "get_table":$this->function_name;
// Set the statement
$this->statement = (!isset($this->statement) || isset($this->statement) && $this->statement == false)? "select * from ".$this->table_name:$this->statement;
// Add on limiting
if($start_from != false && $per_page != false) {
if(is_numeric($start_from) && is_numeric($per_page))
$this->statement .= " LIMIT $start_from, $per_page";
}
// Run your query
$this->run_query($this->statement);
// Reset the variables
$this->reset_class();
return $this;
}
public function select($value = false)
{
$this->sql[] = "select";
$this->function_name = "get_table";
if($value != false) {
$this->sql[] = (!is_array($value))? $value:implode(",",$value);
}
else
$this->sql[] = "*";
return $this;
}
public function from($value = false)
{
$this->sql[] = "from";
$this->sql[] = "$value";
return $this;
}
public function where($values = array(), $not = false, $group = false,$operand = 'and')
{
if(empty($values))
return $this;
$this->sql_where = array();
if(isset($this->sql) && !in_array('where',$this->sql))
$this->sql[] = 'where';
$equals = ($not == false || $not == 0)? "=":"!=";
if(is_array($values) && !empty($values)) {
if(!isset($this->i))
$this->i = 0;
foreach($values as $key => $value) {
$key = trim($key,":");
if(isset($this->bind[":".$key])) {
$auto = str_replace(".","_",$key).$this->i;
// $preop = $operand." ";
}
else {
// $preop = "";
$auto = str_replace(".","_",$key);
}
$this->bind[":".$auto] = $value;
$this->sql_where[] = $key." $equals ".":".$auto;
$this->i++;
}
if($group == false || $group == 0)
$this->sql[] = implode(" $operand ",$this->sql_where);
else
$this->sql[] = "(".implode(" $operand ",$this->sql_where).")";
}
else {
$this->sql[] = $values;
}
if(is_array($this->bind))
asort($this->bind);
return $this;
}
public function limit($value = false,$offset = false)
{
$this->set_limit = "";
if(is_numeric($value)) {
$this->set_limit = $value;
if(is_numeric($offset))
$this->set_limit = $offset.", ".$this->set_limit;
}
return $this;
}
public function order_by($column = array())
{
if(is_array($column) && !empty($column)) {
foreach($column as $colname => $orderby) {
$array[] = $colname." ".str_replace(array("'",'"',"+",";"),"",$orderby);
}
}
else
$array[] = $column;
$this->orderby = implode(", ",$array);
return $this;
}
public function execute()
{
$limit = (isset($this->set_limit) && !empty($this->set_limit))? " LIMIT ".$this->set_limit:"";
$order = (isset($this->orderby) && !empty($this->orderby))? " ORDER BY ".$this->orderby:"";
$this->statement = (is_array($this->sql))? implode(" ", $this->sql).$order.$limit:"";
return $this;
}
public function use_table($table_name = 'employees')
{
$this->table_name = $table_name;
return $this;
}
}
To use:
// Create instance
$query = new Database();
// Big query
$query ->select(array("e.id", "e.employee_name", "e.salary", "dept.department_name", "desi.designation_name", "e.department", "e.designation"))
->from("employees e LEFT OUTER JOIN designations desi ON e.designation = desi.id LEFT OUTER JOIN departments dept ON e.department = dept.id")
->order_by(array("e.employee_name"=>""))
->limit(1,5)->get_table();
// More advanced select
$query ->select(array("id", "designation_name"))
->from("designations")
->order_by(array("designation_name"=>""))
->get_table();
// Simple select
$query ->use_table("departments")
->get_table();
// Simple select with limits
$query ->use_table("departments")
->get_table(10,15);
?>
Gives you:
// Big query
select e.id,e.employee_name,e.salary,dept.department_name,desi.designation_name,e.department,e.designation from employees e LEFT OUTER JOIN designations desi ON e.designation = desi.id LEFT OUTER JOIN departments dept ON e.department = dept.id ORDER BY e.employee_name LIMIT 5, 1
// More advanced select
select id,designation_name from designations ORDER BY designation_name
// Simple select
select * from departments
// Simple select with limits
select * from departments LIMIT 10, 15

Categories