How to join table dynamically in codeigniter? - php

I want to join table dynamically in codeigniter by passing table name as parameter.
below is my controller function to call model function
function index(){
$table=array('branch'=>'branch_id','specialization'=>'spec_branch_id');
$this->model->join($table);
}
and this is my model function
function join($table){
foreach($table as $table_name=>$table_id){
/*i want here table*/
$table1=$table_name;
}
$this->db->select('*');
$this->db->from(''.$table1.' t1');
$this->db->join(''.$table2.' t2','t1.'.$t1id.'=t2.'.$t2id);
return $this->db->get();
echo $this->db->last_query();die;
}
As in above function i want dynamic table name like table1=branch;
table2=specializaton in my model function, so please help me to solve and if someone have another also can share.

here is my custom code dynamically join.
mode form.
<?php public function commonGet($options) {
$select = false;
$table = false;
$join = false;
$order = false;
$limit = false;
$offset = false;
$where = false;
$or_where = false;
$single = false;
$where_not_in = false;
$like = false;
extract($options);
if ($select != false)
$this->db->select($select);
if ($table != false)
$this->db->from($table);
if ($where != false)
$this->db->where($where);
if ($where_not_in != false) {
foreach ($where_not_in as $key => $value) {
if (count($value) > 0)
$this->db->where_not_in($key, $value);
}
}
if ($like != false) {
$this->db->like($like);
}
if ($or_where != false)
$this->db->or_where($or_where);
if ($limit != false) {
if (!is_array($limit)) {
$this->db->limit($limit);
} else {
foreach ($limit as $limitval => $offset) {
$this->db->limit($limitval, $offset);
}
}
}
if ($order != false) {
foreach ($order as $key => $value) {
if (is_array($value)) {
foreach ($order as $orderby => $orderval) {
$this->db->order_by($orderby, $orderval);
}
} else {
$this->db->order_by($key, $value);
}
}
}
if ($join != false) {
foreach ($join as $key => $value) {
if (is_array($value)) {
if (count($value) == 3) {
$this->db->join($value[0], $value[1], $value[2]);
} else {
foreach ($value as $key1 => $value1) {
$this->db->join($key1, $value1);
}
}
} else {
$this->db->join($key, $value);
}
}
}
$query = $this->db->get();
if ($single) {
return $query->row();
}
return $query->result();
} ?>
and view index page
<?php function index(){
$option = array(
'table' => 't1',
'join' => array('t2' => 't2.id = t1.id')
);
$this->model->commonGet($option);
}?>

You can try this code also for two table join.
Controller function.
function index(){
$table=array('branch'=>'branch_id','specialization'=>'spec_branch_id');
$this->model->join($table);
}
Model function
function join($tables){
$i=1;
foreach($tables as $table_name=>$table_id){
${'table'.$i}=$table_name;
${'t'.$i.'id'}=$table_id;
$i++;
}
$this->db->select('*');
$this->db->from(''.$table1.' t1');
$this->db->join(''.$table2.' t2','t1.'.$t1id.'=t2.'.$t2id);
//$this->output->enable_profiler(TRUE);
return $this->db->get();
}

Related

How to add order key for DynaGrid?

I have an ActionColumn for each tables. I need to add order => ORDER_FIX_RIGHT per table for ActionColumn. How can i add order key in my DynaGridViewAdvanced?
I tried to write:
protected function applyColumns()
{
$columns = [];
$newColumns = [];
foreach ($this->columns as $column) {
$order = ArrayHelper::getValue($column, 'order', self::ORDER_MIDDLE);
if ($order == self::ORDER_FIX_LEFT) {
$newColumns[] = $column;
unset($column['order']);
$columns[] = $column;
}
}
foreach ($this->_visibleKeys as $key) {
if (empty($this->_columns[$key])) {
continue;
}
$column = $this->_columns[$key];
$newColumns[] = $column;
if (isset($column['order'])) {
unset($column['order']);
}
if (isset($column['visible'])) {
unset($column['visible']);
}
$columns[] = $column;
}
foreach ($this->columns as $column) {
$order = ArrayHelper::getValue($column, 'order', self::ORDER_MIDDLE);
$isActionColumn = is_array($column) && array_key_exists('class', $column) && (new $column['class']) instanceof ActionColumn;
if ($order == self::ORDER_FIX_RIGHT) {
$newColumns[] = $column;
unset($column['order']);
$columns[] = $column;
}
if ($isActionColumn) {
$column['order'] = self::ORDER_FIX_RIGHT;
$newColumns[] = $column;
unset($column['order']);
$columns[] = $column;
}
}
$this->columns = $newColumns;
$this->gridOptions['columns'] = $columns;
}
But it makes second column. If i write:
protected function prepareColumns()
{
$this->_columns = $this->columns;
$columns = [];
foreach ($this->columns as $column) {
$isActionColumn = is_array($column) && array_key_exists('class', $column) && (new $column['class']) instanceof ActionColumn;
if (is_array($column) && !$isActionColumn) {
unset($column['order']);
}
if ($isActionColumn) {
$column['order'] = $this->actionColumnsPosition;
}
$columns[] = $column;
}
$this->gridOptions['columns'] = $columns;
}
All working fine, but when i change some in columns, i have exception about:
Setting unknown property ...ActionColumn::order
Done. I created method setDefaultOrderToActionColumns with content:
private function setDefaultOrderToActionColumns() {
foreach ($this->columns as &$column) {
$columnTypeIsAction = is_array($column) && array_key_exists('class', $column) && (new $column['class']) instanceof ActionColumn;
if ($columnTypeIsAction) {
$column['order'] = $this->actionColumnsPosition;
}
}
}
And called it in redefined method run:
public function run() {
...
$this->setDefaultOrderToActionColumns();
}

Sort multidimensional array by another array and complete missing keys in the same order

I'm trying to export data from leads table to excel using PHP/Laravel, the leads table caמ be customized to show specific columns and the export columns should be same as the table columns. the problem is - if column not exists in a specific row the column not shown empty and the 'xls' file is exported really messy...
my code looks like this:
public function excelExport(Request $request, $client_id=null)
{
$client_id = is_null($client_id) ? \Auth::client()->id : $client_id;
if(is_null($this->client_users)){
$this->client_users = $this->clientsController->listClientUsers($client_id);
}
$columns = $this->account_settings->getColumnsDef($client_id);
$query = Lead::select(array_keys($columns))->where('client_id',strval($client_id))->where('deleted',0);
$query = $this->setQueryDates($request,$query,$client_id);
$query = $this->leadsFiltersController->setExportQuery($request,$query);
$arr = $query->get()->toArray();
Excel::create('leads' , function($excel) use ($arr,$columns){
$excel->sheet('Leads' , function($sheet) use ($arr,$columns){
$rows = [];
$count = 0;
foreach($arr as $lead){
$row = $this->setExportRowData($lead,$count,$columns);
$rows[] = $row;
$count++;
}
$sheet->fromArray($rows);
});
})->export('xls');
private function setExportRowData($lead,$count,$columns,$order = true)
{
$row = [];
$order = null;
foreach($lead as $k => $v) {
if (is_array($v)) {
switch (strtolower($k)) {
case "ga_details":
if (count($v) > 2) {
foreach ($v as $key => $ga_detail) {
if ($key != "realTime_data" && $key != "uacid") {
$row[$key] = $ga_detail;
}
}
}
break;
case "status":
if (isset($v['name']) && count($v['name'])) {
$row['status'] = $v['name'];
} else {
$row['status'] = "no status";
}
break;
case "owner":
if (isset($v['owner_id']) && count($v)) {
$row['owner'] = $this->getClientOwnerUserName($this->client_users, $v['owner_id']);
} else {
$row['owner'] = "no owner";
}
break;
case "prediction":
if (isset($v['score']) && count($v)) {
$row['prediction'] = $v['score'];
} else {
$row['prediction'] = "no prediction";
}
break;
case "the_lead":
foreach ($v as $key => $lead_detail) {
$row[$key] = $lead_detail;
}
break;
case "quality":
if (isset($v['name'])) {
$row['quality'] = $v['name'];
} else {
$row['quality'] = "no quality";
}
break;
case "feeds":
if (isset($v['feeds']) && count($v['feeds'])) {
$row['feeds'] = array_pop($v['feeds'])['message'];
}
break;
default :
$row[$k] = $v;
break;
}
} else {
if ($k != "_id") {
$row[$k] = $v;
}
}
}
return $order == true ? sortArrayByArrayValues($this->order,$row) : $row;
}
sortArrayByArrayValues function looks like this:
function sortArrayByArrayValues(Array $array, Array $orderArray)
{
$rtn = [];
foreach($array as $arr){
if(isset($orderArray[$arr])){
$rtn[$arr] = $orderArray[$arr];
}else{
$rtn[$arr] = '';
}
}
return $rtn;
}
I really have no clue how to solve it, appreciate any help!!! :)

Fatal error: Call to a member function num_rows() on a non-object in /home/*/public_html/application/core/MY_Controller.php on line 137

I'am getting:
Fatal error: Call to a member function num_rows() on a non-object in /home/nbaxy/public_html/application/core/MY_Controller.php on line 137
MY_Controller.php:
<?php
class MY_Controller extends CI_Controller
{
private $dblabg = array();
public function __construct()
{
parent::__construct();
if($this->config->item("use_database") == 1)
{
$this->load->database();
$this->load->model("dashboard/admin");
$this->set_config();
if($this->config->item("module_user_online") == 1 )
{
$this->set_online();
}
}
$this->set_lang();
$this->clean_cache();
if($this->router->fetch_module() == 'dashboard')
{
$this->__dashboard();
}
}
protected function set_lang()
{
if($this->config->item("user_change_lang") == "1")
{
if($this->input->get("lang"))
{
if(in_array($this->input->get("lang"),$this->config->item("langs_available")) || $this->config->item("use_db_language") == '1')
{
$this->config->set_item("lang",$this->input->get("lang"));
$this->session->set_userdata('lang', $this->input->get("lang"));
}
}
else
{
if($this->session->userdata('lang') != '')
{
$this->config->set_item("lang",$this->session->userdata('lang'));
}
else
{
if($this->config->item("language_browser") == '1' )
{
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$temp = $this->admin->getTable('languages',array("iso" => $lang));
if($temp->num_rows()>0 && $this->config->item("language_browser") == '1' && $this->router->fetch_module() != 'dashboard')
{
$d = $temp->row();
$this->config->set_item("lang",$d->language);
}
}
}
}
}
if($this->config->item("use_db_language") == '1')
{
$this->load_db_language($this->config->item("lang"));
}
else
$this->lang->load($this->config->item("lang"),$this->config->item("lang"));
}
public function load_db_language($lang = 'english')
{
$this->db->select ('*');
$this->db->from ('language');
$this->db->where ('language', $lang);
$query = $this->db->get()->result();
foreach ( $query as $row )
{
$return[$row->key] = $row->text;
}
$this->dblabg = $return;
$this->db->select ('*');
$this->db->from ('languages');
$query = $this->db->get()->result();
$return = array();
foreach ( $query as $row )
{
$return[$row->language] = $row->language;
}
$this->config->set_item("langs_available", $return);
unset($query,$return);
}
public function get_label($key)
{
return $this->dblabg[$key];
}
protected function clean_cache()
{
if(exec('echo EXEC') == 'EXEC')
{
if($this->config->item("clean_cache") != '0')
{
exec("find ".getcwd()." -type f -name '*.cache' -mtime +".$this->config->item("clean_cache")." -exec rm {} \;");
}
}
}
protected function set_online()
{
$this->admin->setUsuarioOnline(intval($this->session->userdata('id')));
}
protected function set_config()
{
$config = $this->admin->getTable("settings");
if($config->num_rows() == 0)
{
show_error("No settings founds in your database, you need install this script on clean database",400);
}
foreach ($config->result_array() as $row)
{
if($row['var'] != 'use_database')
{
if($row['var'] == 'langs_available')
{
$this->load->helper('directory');
$langs = directory_map('./application/language');
foreach ($langs as $key => $value) {
$temp[] = $key;
}
$row['value'] = $temp;
}
if($row['var'] == 'theme')
{
if($_GET['skin'])
{
$row['value'] = $_GET['skin'];
}
}
if(!is_array($row['value']))
{
//$row['value'] = str_ireplace('"', "'",$row['value']);
$row['value'] = str_ireplace('\"', '"',$row['value']);
$row['value'] = str_ireplace("\'", "'",$row['value']);
$row['value'] = html_entity_decode($row['value']);
}
$this->config->set_item($row['var'], $row['value']);
if($this->agent->is_mobile())
{
$this->config->set_item("theme", $this->config->item("theme_mobile"));
}
}
}
if($this->agent->is_mobile())
{
if($this->config->item("mobile_redirect") != '')
redirect($this->config->item("mobile_redirect"), 'location', 301);
}
if(is_logged())
{
$this->config->set_item("biography_lang_temp",$this->config->item("biography_lang"));
$this->config->set_item("biography_lang", $this->session->userdata('biography_lang'));
}
$config = Array(
'protocol' => 'smtp',
'smtp_host' => $this->config->item("smtp_host"),
'smtp_port' => $this->config->item("smtp_port"),
'smtp_user' => $this->config->item("smtp_user"), // change it to yours
'smtp_pass' => $this->config->item("smtp_pass"), // change it to yours
'mailtype' => 'html',
'charset' => 'utf-8',
'wordwrap' => TRUE
);
$this->load->library('email',$config);
}
protected function __dashboard()
{
if($this->config->item("use_database") == 0)
{
show_404();
}
if(!is_logged() && $this->router->method != 'login' && $this->router->method != 'logout' )
{
redirect(base_url()."dashboard/login");
}
if($this->session->userdata('is_admin') != 1 && $this->router->method != 'login')
{
//redirect(base_url(),"refresh");
redirect(base_url()."dashboard/login");
}
else{
if($this->session->userdata('username') == 'demo#jodacame.com' && $this->router->method != 'login')
{
if($this->router->method == 'website')
{
$this->config->set_item("lastfm", 'lastfmdemomodeapikey');
}
if($_POST || $this->router->method == 'smtp' || $this->router->method == 'license' || $this->router->method =='users' || $this->router->method =='lyrics' || $this->router->method == 'newsletter' )
{
show_error("Demo Account don't have permission for this action",403);
}
}
// Upgrade
if(file_exists("upgrade/upgrade.sql"))
{
$MD5 = md5_file("upgrade/upgrade.sql");
if($this->config->item("md5updated") != $MD5)
{
$sql = file_get_contents("upgrade/upgrade.sql");
$sqls = explode(";\n",$sql);
foreach ($sqls as $key => $value) {
if($value != '')
{
$this->db->query($value);
//echo $this->db->last_query()."<br>";
}
}
$this->db->query("UPDATE settings SET value = '$MD5' WHERE var='md5updated';");
$this->session->sess_destroy();
//echo $this->db->last_query()."<br>";
redirect(base_url()."dashboard/login/1");
}
}
if(file_exists("install.sql"))
{
$sql = file_get_contents("install.sql");
$sqls = explode(";\n",$sql);
foreach ($sqls as $key => $value) {
if($value != '')
{
$this->db->query($value);
//echo $this->db->last_query()."<br>";
}
}
unlink("install.sql");
redirect(base_url()."dashboard/login/2");
}
// Check install modules
}
}
}
Please tell me, how can i fix this?
The problem is you are calling "$temp->num_rows()" Your Variable $temp is not a result set from a Database Query. You are calling a method that doesn't exist. It seems you are trying to get the number of rows of data that are on the table 'languages'. In this case you would need to execute a $SQL query.
Example:
// this assumes $mysqli is a successfull connection to the table 'languages'
$query = "SELECT COUNT(id) FROM `languages`";
if ($result = $mysqli->query($query)) {
$row_cnt = $result->num_rows; //$row_cnt now equals an integer.
}
*Note: You need to replace $temp->numrows with if($row_cnt > 0...)

KendoUI Grid Server Side Sort/Filter not applying to the SQL Query

I'm running into a Problem that my grid isn't Sorting/Filtering as expected. I always get all results back from the database.
Here is my JS:
<script>
'use strict';
(function($, kendo) {
$("#grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url:"http://server01/read.php",
type: "POST"
}
},
schema: {
data: "data",
total: "total",
model: {
fields: {
tID: { type: "number" },
tTitle: { type: "string" },
oDate: { type: "date" },
eDate: { type: "date" },
cDate: { type: "date" },
tKeywords: { type: "string" }
}
}
},
pageSize: 2,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
height: 430,
filterable: true,
sortable: true,
pageable: true,
columns: [{
field:"tID",
title:"TicketID",
width:"60px",
filterable: false
},{
field: "tTitle",
title: "Ticket Bezeichnung"
}, {
field: "oDate",
title: "Ticket eröffnet",
format: "{0:MM/dd/yyyy}",
width: "160px"
}, {
field: "eDate",
title: "Ticket escaliert",
format: "{0:MM/dd/yyyy}",
width: "160px"
}, {
field: "cDate",
title: "Ticket geschlossen",
format: "{0:MM/dd/yyyy}",
width: "160px"
}, {
field: "tKeywords",
title: "keywords"
}
]
});
})(jQuery, kendo);
On the Server side it looks like this:
error_reporting(E_ALL);
include 'classes/classes.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
header('Content-Type: application/json');
$request = json_encode($_POST);
$result = new DataSourceResult('mysql:host=localhost;dbname=jarvis','root','',array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
echo json_encode($result->read('jar_ticketing_index', array('tID', 'tTitle', 'tDesc', 'oDate', 'eDate', 'cDate','tKeywords'), $request));
}else{
echo "Opps...";
}
For applying the filters to the Query I'm using the dataSourceResult class:
class DataSourceResult {
private $db;
private $stringOperators = array(
'eq' => 'LIKE',
'neq' => 'NOT LIKE',
'doesnotcontain' => 'NOT LIKE',
'contains' => 'LIKE',
'startswith' => 'LIKE',
'endswith' => 'LIKE'
);
private $operators = array(
'eq' => '=',
'gt' => '>',
'gte' => '>=',
'lt' => '<',
'lte' => '<=',
'neq' => '!='
);
private $aggregateFunctions = array(
'average' => 'AVG',
'min' => 'MIN',
'max' => 'MAX',
'count' => 'COUNT',
'sum' => 'SUM'
);
function __construct($dsn, $username=null, $password=null, $driver_options=null) {
$this->db = new PDO($dsn, $username, $password, $driver_options);
}
private function total($tableName, $properties, $request) {
if (isset($request->filter)) {
$where = $this->filter($properties, $request->filter);
$statement = $this->db->prepare("SELECT COUNT(*) FROM $tableName $where");
$this->bindFilterValues($statement, $request->filter);
} else {
$statement = $this->db->prepare("SELECT COUNT(*) FROM $tableName");
}
$statement->execute();
$total = $statement->fetch(PDO::FETCH_NUM);
return (int)($total[0]);
}
private function page() {
return ' LIMIT :skip,:take';
}
private function group($data, $groups, $table, $request, $properties) {
if (count($data) > 0) {
return $this->groupBy($data, $groups, $table, $request, $properties);
}
return array();
}
private function mergeSortDescriptors($request) {
$sort = isset($request->sort) && count($request->sort) ? $request->sort : array();
$groups = isset($request->group) && count($request->group) ? $request->group : array();
return array_merge($sort, $groups);
}
private function groupBy($data, $groups, $table, $request, $properties) {
if (count($groups) > 0) {
$field = $groups[0]->field;
$count = count($data);
$result = array();
$value = $data[0][$field];
$aggregates = isset($groups[0]->aggregates) ? $groups[0]->aggregates : array();
$hasSubgroups = count($groups) > 1;
$groupItem = $this->createGroup($field, $value, $hasSubgroups, $aggregates, $table, $request, $properties);
for ($index = 0; $index < $count; $index++) {
$item = $data[$index];
if ($item[$field] != $value) {
if (count($groups) > 1) {
$groupItem["items"] = $this->groupBy($groupItem["items"], array_slice($groups, 1), $table, $request, $properties);
}
$result[] = $groupItem;
$groupItem = $this->createGroup($field, $data[$index][$field], $hasSubgroups, $aggregates, $table, $request, $properties);
$value = $item[$field];
}
$groupItem["items"][] = $item;
}
if (count($groups) > 1) {
$groupItem["items"] = $this->groupBy($groupItem["items"], array_slice($groups, 1), $table, $request, $properties);
}
$result[] = $groupItem;
return $result;
}
return array();
}
private function addFilterToRequest($field, $value, $request) {
$filter = (object)array(
'logic' => 'and',
'filters' => array(
(object)array(
'field' => $field,
'operator' => 'eq',
'value' => $value
))
);
if (isset($request->filter)) {
$filter->filters[] = $request->filter;
}
return (object) array('filter' => $filter);
}
private function addFieldToProperties($field, $properties) {
if (!in_array($field, $properties)) {
$properties[] = $field;
}
return $properties;
}
private function createGroup($field, $value, $hasSubgroups, $aggregates, $table, $request, $properties) {
if (count($aggregates) > 0) {
$request = $this->addFilterToRequest($field, $value, $request);
$properties = $this->addFieldToProperties($field, $properties);
}
$groupItem = array(
'field' => $field,
'aggregates' => $this->calculateAggregates($table, $aggregates, $request, $properties),
'hasSubgroups' => $hasSubgroups,
'value' => $value,
'items' => array()
);
return $groupItem;
}
private function calculateAggregates($table, $aggregates, $request, $properties) {
$count = count($aggregates);
if (count($aggregates) > 0) {
$functions = array();
for ($index = 0; $index < $count; $index++) {
$aggregate = $aggregates[$index];
$name = $this->aggregateFunctions[$aggregate->aggregate];
$functions[] = $name.'('.$aggregate->field.') as '.$aggregate->field.'_'.$aggregate->aggregate;
}
$sql = sprintf('SELECT %s FROM %s', implode(', ', $functions), $table);
if (isset($request->filter)) {
$sql .= $this->filter($properties, $request->filter);
}
$statement = $this->db->prepare($sql);
if (isset($request->filter)) {
$this->bindFilterValues($statement, $request->filter);
}
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
return $this->convertAggregateResult($result[0]);
}
return (object)array();
}
private function convertAggregateResult($properties) {
$result = array();
foreach($properties as $property => $value) {
$item = array();
$split = explode('_', $property);
$field = $split[0];
$function = $split[1];
if (array_key_exists($field, $result)) {
$result[$field][$function] = $value;
} else {
$result[$field] = array($function => $value);
}
}
return $result;
}
private function sort($properties, $sort) {
$count = count($sort);
$sql = '';
if ($count > 0) {
$sql = ' ORDER BY ';
$order = array();
for ($index = 0; $index < $count; $index ++) {
$field = $sort[$index]->field;
if (in_array($field, $properties)) {
$dir = 'ASC';
if ($sort[$index]->dir == 'desc') {
$dir = 'DESC';
}
$order[] = "$field $dir";
}
}
$sql .= implode(',', $order);
}
return $sql;
}
private function where($properties, $filter, $all) {
if (isset($filter->filters)) {
$logic = ' AND ';
if ($filter->logic == 'or') {
$logic = ' OR ';
}
$filters = $filter->filters;
$where = array();
for ($index = 0; $index < count($filters); $index++) {
$where[] = $this->where($properties, $filters[$index], $all);
}
$where = implode($logic, $where);
return "($where)";
}
$field = $filter->field;
if (in_array($field, $properties)) {
$index = array_search($filter, $all);
$value = ":filter$index";
if ($this->isDate($filter->value)) {
$field = "date($field)";
$value = "date($value)";
}
if ($this->isString($filter->value)) {
$operator = $this->stringOperators[$filter->operator];
} else {
$operator = $this->operators[$filter->operator];
}
return "$field $operator $value";
}
}
private function flatten(&$all, $filter) {
if (isset($filter->filters)) {
$filters = $filter->filters;
for ($index = 0; $index < count($filters); $index++) {
$this->flatten($all, $filters[$index]);
}
} else {
$all[] = $filter;
}
}
private function filter($properties, $filter) {
$all = array();
$this->flatten($all, $filter);
$where = $this->where($properties, $filter, $all);
return " WHERE $where";
}
private function isDate($value) {
$result = date_parse($value);
return $result["error_count"] < 1;
}
private function isString($value) {
return !is_bool($value) && !is_numeric($value) && !$this->isDate($value);
}
private function bindFilterValues($statement, $filter) {
$filters = array();
$this->flatten($filters, $filter);
for ($index = 0; $index < count($filters); $index++) {
$value = $filters[$index]->value;
$operator = $filters[$index]->operator;
$date = date_parse($value);
if ($operator == 'contains' || $operator == 'doesnotcontain') {
$value = "%$value%";
} else if ($operator == 'startswith') {
$value = "$value%";
} else if ($operator == 'endswith') {
$value = "%$value";
}
$statement->bindValue(":filter$index", $value);
}
}
public function create($table, $properties, $models, $key) {
$result = array();
$data = array();
if (!is_array($models)) {
$models = array($models);
}
$errors = array();
foreach ($models as $model) {
$columns = array();
$values = array();
$input_parameters = array();
foreach ($properties as $property) {
if ($property != $key) {
$columns[] = $property;
$values[] = '?';
$input_parameters[] = $model->$property;
}
}
$columns = implode(', ', $columns);
$values = implode(', ', $values);
$sql = "INSERT INTO $table ($columns) VALUES ($values)";
$statement = $this->db->prepare($sql);
$statement->execute($input_parameters);
$status = $statement->errorInfo();
if ($status[1] > 0) {
$errors[] = $status[2];
} else {
$model->$key = $this->db->lastInsertId();
$data[] = $model;
}
}
if (count($errors) > 0) {
$result['errors'] = $errors;
} else {
$result['data'] = $data;
}
return $result;
}
public function destroy($table, $models, $key) {
$result = array();
if (!is_array($models)) {
$models = array($models);
}
$errors = array();
foreach ($models as $model) {
$sql = "DELETE FROM $table WHERE $key=?";
$statement = $this->db->prepare($sql);
$statement->execute(array($model->$key));
$status = $statement->errorInfo();
if ($status[1] > 0) {
$errors[] = $status[2];
}
}
if (count($errors) > 0) {
$result['errors'] = $errors;
}
return $result;
}
public function update($table, $properties, $models, $key) {
$result = array();
if (in_array($key, $properties)) {
if (!is_array($models)) {
$models = array($models);
}
$errors = array();
foreach ($models as $model) {
$set = array();
$input_parameters = array();
foreach ($properties as $property) {
if ($property != $key) {
$set[] = "$property=?";
$input_parameters[] = $model->$property;
}
}
$input_parameters[] = $model->$key;
$set = implode(', ', $set);
$sql = "UPDATE $table SET $set WHERE $key=?";
$statement = $this->db->prepare($sql);
$statement->execute($input_parameters);
$status = $statement->errorInfo();
if ($status[1] > 0) {
$errors[] = $status[2];
}
}
if (count($errors) > 0) {
$result['errors'] = $errors;
}
}
if (count($result) == 0) {
$result = "";
}
return $result;
}
public function read($table, $properties, $request = null) {
$result = array();
$result['total'] = $this->total($table, $properties, $request);
$sql = sprintf('SELECT %s FROM %s', implode(', ', $properties), $table);
if (isset($request->filter)) {
$sql .= $this->filter($properties, $request->filter);
}
$sort = $this->mergeSortDescriptors($request);
if (count($sort) > 0) {
$sql .= $this->sort($properties, $sort);
}
if (isset($request->skip) && isset($request->take)) {
$sql .= $this->page();
}
$statement = $this->db->prepare($sql);
if (isset($request->filter)) {
$this->bindFilterValues($statement, $request->filter);
}
if (isset($request->skip) && isset($request->take)) {
$statement->bindValue(':skip', (int)$request->skip, PDO::PARAM_INT);
$statement->bindValue(':take', (int)$request->take, PDO::PARAM_INT);
}
$statement->execute();
$data = $statement->fetchAll(PDO::FETCH_ASSOC);
if (isset($request->group) && count($request->group) > 0) {
$data = $this->group($data, $request->group, $table, $request, $properties);
$result['groups'] = $data;
} else {
$result['data'] = $data;
}
if (isset($request->aggregate)) {
$result["aggregates"] = $this->calculateAggregates($table, $request->aggregate, $request, $properties);
}
return $result;
}
}
I always get all of the records back from the database. It looks like my DataSourceResult Object isn't getting the filter variables the right way. But I don't see any error at all.
Could you give me a hint?
Oke I pointed it out. The Filter I got by POST need to be passed as an object to the dataSourceResult Class.
$object = json_decode(json_encode($_POST), FALSE);
Now its working like a charm!

I'm using text file as db # php,but sometimes it fails to save

Hi I am using serialize & unserialize functions and fwrite & fopen for text based db
<?php
ini_set('display_errors', 'on');
header('Content-Type: text/html; charset=utf-8');
$debugged = (bool) isset($_GET['debug']);
error_reporting($debugged ? E_ALL : 0);
$data_filename = "database.txt";
$admins = array(
"admin" => "admin",
"admin2" => "admin2"
);
$superadmin = "admin";
$order = "asc";
include_once "functions.php";
?>
<?php
function clean($d) {
return str_replace(array(
"\t",
"\n",
"\s",
"\r"
), "", $d);
}
function add($email, $age_id, $gender_id, $city, $prof_id, $model, $token, $os_version, $udid, $admin) {
global $data_filename;
$datax['email'] = $email;
$datax['age_id'] = $age_id;
$datax['gender_id'] = $gender_id;
$datax['city'] = $city;
$datax['prof_id'] = $prof_id;
$datax['model'] = $model;
$datax['token'] = $token;
$datax['os_version'] = $os_version;
$datax['udid'] = $udid;
$datax['admin'] = $admin;
$data = array();
$data_content = get_file_content($data_filename);
if ($data_content !== NULL)
$data = unserialize($data_content);
$entrie = serialize($datax);
$data[] = $entrie;
$data_content = serialize($data);
put_file_content($data_filename, $data_content);
return $data_content;
}
function get_file_content($filename) {
if (!file_exists($filename))
fclose(fopen($filename, "w"));
if (!file_exists($filename))
die("sie.");
$content = (filesize($filename) > 0) ? #fread(fopen($filename, "r+"), filesize($filename)) : NULL;
if ($content === false)
die("aq");
return $content;
}
if (!$data_filename) {
die("sie-31");
}
$datasey = array();
$data_content = get_file_content($data_filename);
if ($data_content !== NULL)
$datasey = #unserialize($data_content);
function put_file_content($filename, $content) {
if (file_put_contents($filename, $content, LOCK_EX)) {
return true;
} else {
usleep(250000);
put_file_content($filename, $content, LOCK_EX);
}
}
function reverse_data($data) {
$data = array_reverse($data);
foreach ($data as $key => $entrie)
$key = $entries_num - $key - 1;
return $data;
}
function del_admin_contents($who) {
global $admin, $superadmin, $data_filename;
;
$array = array();
$data_content = get_file_content($data_filename);
if ($data_content === NULL)
return;
$array = unserialize($data_content);
foreach ($array as $key => $value) {
$bok = unserialize($value);
if ($bok["admin"] == $who) {
unset($array[$key]);
}
}
$temp = array();
foreach ($array as $value)
$temp[] = $value;
$data_content = serialize($array);
put_file_content($data_filename, $data_content);
return $data_content;
}
function del_entries($select, $udid) {
global $data_filename;
$data = array();
$data_content = get_file_content($data_filename);
if ($data_content === NULL)
return;
$data = unserialize($data_content);
$data = del_id($data, $select, $udid);
$data_content = serialize($data);
put_file_content($data_filename, $data_content);
return $data_content;
}
function del_id($array, $id_array, $udid) {
global $admin, $superadmin;
foreach ($id_array as $id)
if (isset($array[$id])) {
$bok = unserialize($array[$id]);
if ($bok["admin"] == $admin || $admin == $superadmin) {
if ($bok["udid"] == $udid) {
unset($array[$id]);
}
}
}
$temp = array();
foreach ($array as $value)
$temp[] = $value;
return $temp;
}
function up_id($array, $new_array, $id) {
global $admin, $superadmin;
if (isset($array[$id])) {
$array[$id] = serialize($new_array);
}
return $array;
}
function update_id($data, $id, $new_array) {
global $data_filename;
$data = up_id($data, $new_array, $id);
$data_content = serialize($data);
put_file_content($data_filename, $data_content);
return true;
}
function emailupdate($udid, $email) {
global $data_filename;
$data = array();
$ret = false;
$data_content = get_file_content($data_filename);
if ($data_content === NULL)
return false;
$data = unserialize($data_content);
$id = 0;
foreach ($data as $d) {
$new_array = unserialize($d);
if ($new_array["udid"] == $udid) {
$new_array["email"] = $email;
update_id($data, $id, $new_array);
$ret = true;
}
$id++;
}
return $ret;
}
function alldata() {
global $datasey;
$benimdata = array();
if (count($datasey) > 0) {
foreach ($datasey as $key => $entrie) {
$gec = unserialize($entrie);
$benimdata[] = $gec;
}
return $benimdata;
} else {
return false;
}
}
function cleaner() {
global $data_filename, $max_entries;
if ($max_entries == 0)
return;
$data = array();
$data_content = get_file_content($data_filename);
if ($data_content !== NULL)
$data = unserialize($data_content);
while (count($data) >= $max_entries)
$data = clear_id($data, array(
0
));
$data_content = serialize($data);
put_file_content($data_filename, $data_content);
return true;
}
function logincheck($user, $pass) {
global $admins;
if (array_key_exists($user, $admins)) {
if ($admins[$user] == $pass) {
return true;
} else {
return false;
}
} else {
return false;
}
}
$backup = "./backup/" . date("Ymd-H:i") . ".dat";
if (!file_exists($backup)) {
$backup_data_content = get_file_content($data_filename);
file_put_contents($backup, $backup_data_content, LOCK_EX);
}
?>
As here is an example of how I add new value(s):
$data_content=add($_POST["email"],$_POST["age_id"],$_POST["gender_id"],$_POST["city_id"],$_POST["prof_id"],$_POST["model"],"N/A",$_POST["os_version"],$randomudid,$admin);
for delete :
$data_content=del_entries(array($_GET["del"]),$_GET["delete"]);
My question is when 2 admins try to enter a value at the same time it writes to database only the last value sent and deletes the old values, how can I resolve this issue?

Categories