showing my models value on view in codeigniter - php

im new in codeigniter and get some trouble with my function
here is my model
public function kode_unik(){
$q = $this->db->query("select MAX(RIGHT(id_obat,5)) as code_max from obat");
$code = "";
if($q->num_rows()>0){
foreach($q->result() as $cd){
$tmp = ((int)$cd->code_max)+1;
$hitung = strlen($tmp);
if ($hitung == 1 ){
$a = "0000".$tmp;
} elseif ($hitung == 2) {
$a = "000".$tmp;
}elseif ($hitung == 3) {
$a = "00".$tmp;
}elseif ($hitung == 4) {
$a = "0".$tmp;
}else{
$a = $tmp;
}
$code = sprintf("%s", $a);
}
}else{
$code = "0001";
}
$kodenyami = "E".$code;
return $kodenyami;
}
and then i wanna get the result of my models to show in my view.
here is my controller
public function add_data()
{
$this->load->helper( array('fungsidate', 'rupiah', 'url') );
$this->load->model('obat');
$this->load->database();
$data['a'] = $this->obat->tampil_data();
$data['b'] = $this->obat->kode_unik();
$componen = array(
"header" => $this->load->view("admin/header", array(), true),
"sidebar" => $this->load->view("admin/sidebar", array(), true),
"content" => $this->load->view("admin/add_obat", array("data" => $data), true)
);
$this->load->view('admin/index', $componen);
}
and my view goes here.
<i class="fa fa-medkit fa-5x"></i></div>
<div class="col-xs-9 text-right">
line20-> <div class="huge"><?php echo $b; ?></div>
<div>ID Obat</div>
the code give me an errors Message: Undefined variable: b
just don't know how to put the value of my models $kode_unik into my view ..
thanks

$data is already an array. Maybe like this :
"content" => $this->load->view("admin/add_obat", $data, TRUE)
CodeIgniter will extract the keys in $data so you will be able to use them in your view as $b
BTW instead of passing array() as a parameter of the load->view you can use NULL
P.S If you set the last parameter to TRUE, you will return the populated content of that view as a String (HTML in that case)
Here is something to start with :
public function __construct() {
parent::construct();
$this->load->helper(‘array(‘fungsidate’, ‘rupiah’, ‘url’);
$this->load->model(‘obat’);
$this->load->database(); // Should be already loaded depending on your config
}
public function add_data() {
// Set the data
$data[‘a’] = $this->obat->tampil_data();
$data[‘b’] = $this->obat->kodeunik();
// Load the views
$componen = array(
‘header’ => $this->load->view(‘admin/header’, NULL, TRUE);
‘sidebar’ => $this->load->view(‘admin/sidebar’, NULL, TRUE);
‘content’ => $this->load->view(‘admin/add_obat', $data, TRUE);
);
$this->load->view(‘admin/index’ ,$componen);
}
From what I understand about your code, in your templates you will need to echo the array keys
in admin/header you will echo $header;
in admin/sidebar you will echo $sidebar;
in admin/add_obat you will need to echo $content
and then you admin/index should be populated. I won’t do that if I were you to be honest I would probably load each template as is instead of outputting them as HTML string inside the final index. I don’t know exactly how you did your structure so it’s kinda hard for me to guess well. But in my case I would have use something like this instead of the componen array
public function add_data() {
// Set the data
$data[‘a’] = $this->obat->tampil_data();
$data[‘b’] = $this->obat->kodeunik();
// Load the views
$this->load->view(‘admin/header’);
$this->load->view(‘admin/sidebar’);
$this->load->view(‘admin/add_obat, $data); // This should be the body template of your page
$this->load->view(‘admin/footer’); // I guess you have a footer template
}
I hope this will help you!

Related

Load additional data into the view

I have this PHP code where I am loading a quiz into the view. When I select and submit an answer the view is changed and displays only the correct message or the wrong one.
What I am trying to achieve is when clicking the submit button for the answer, to keep the question and just display under if correct or not.
This is the code that I have:
function guess()
{
$guess = $this->input->get('name',false);
$personid = $this->input->get('id',false);
if ($guess === null) {
$newguess['data'] = $this->Starmodel->getQuestion();
$this->load->view('starview',$newguess);
}
else {
$res= $this->Starmodel->isCorrectAnswer($personid,$guess);
$person = $this->load->view('starview', array('iscorrect' => $res,
'name' => $guess));
}
}
My main view is starview.php. Can I use divs and target a specific load a view inside the specific div? How can I do this?
Thank you
Let say this your startview view...
//Your question goes here
//Answer part
<?php if($this->input->post()):
echo $answer_view_data
endif; ?>
In your function guess()
function guess()
{
$guess = $this->input->get('name',false);
$personid = $this->input->get('id',false);
if ($guess === null) {
$newguess['data'] = $this->Starmodel->getQuestion();
$this->load->view('starview',$newguess);
}
else {
$res= $this->Starmodel->isCorrectAnswer($personid,$guess);
$answer_data = 'Sample answer data';
$person = $this->load->view('starview', array('iscorrect' => $res,
'name' => $guess, 'answer_data' => $answer_data));
}
}

codeigniter - calling two functions from same controller one after the other, second function fails

This one's got me stuck!
I have two functions in a controller which can be called from a menu independantly and they work fine.
I want to call them in a month end routine (in the same controller), one after the other; the first function works fine and returns to the calling function, the second function is called but fails because the load of the $model variable fails.
Here is the code for the month end routine,
function month_end_routines()
{
// create stock inventory valuation report in excel format
$export_excel = 1;
$this -> inventory_summary($export_excel);
// create negative stock
$export_excel = 1;
$this -> inventory_negative_stock($export_excel);
echo 'debug 2';
// reset rolling inventory indicator
$this -> load->model('Item');
$this -> load->library('../controllers/items');
$this -> items->reset_rolling();
}
Here is the code for the first function called inventory_summary,
function inventory_summary($export_excel=0, $create_PO=0, $set_NM=0, $set_SM=0)
{
// load appropriate models and libraries
$this -> load->model('reports/Inventory_summary');
$this -> load->library('../controllers/items');
// set variables
$model = $this->Inventory_summary;
$tabular_data = array();
$edit_file = 'items/view/';
$width = $this->items->get_form_width();
$stock_total = 0;
// get all items
$report_data = $model->getData(array());
foreach($report_data as $row)
{
$stock_value = $row['cost_price'] * $row['quantity'];
$stock_total = $stock_total + $stock_value;
// set up the item_number to handle blanks
if ($row['item_number'] == NULL) {$row['item_number'] = $this->lang->line('common_edit');}
$tabular_data[] = array (
$row['category'],
anchor (
$edit_file.$row['item_id'].'/width:'.$width,
$row['item_number'],
array('class'=>'thickbox','title'=>$this->lang->line('items_update'))
),
$row['reorder_policy'],
$row['name'],
$row['cost_price'],
$row['quantity'],
$stock_value,
$stock_total
);
}
$today_date = date('d/m/Y; H:i:s', time());
$data = array (
"title" => $this->lang->line('reports_inventory_summary_report'),
"subtitle" => ' - '.$today_date.' '.$this->lang->line('common_for').' '.$this->db->database.'.',
"headers" => $model->getDataColumns(),
"data" => $tabular_data,
"summary_data" => $model->getSummaryData(array()),
"export_excel" => $export_excel
);
if ($export_excel == 1)
{
$this->load->model('Common_routines');
$this->Common_routines->create_csv($data);
}
else
{
$this->load->view("reports/tabular", $data);
}
return;
.. and here is the code for the second function,
function inventory_negative_stock($export_excel=0, $create_PO=0, $set_NM=0, $set_SM=0)
{
echo 'debug 1.5';
$this -> load->model('reports/Inventory_negative_stock');
$this -> load->library('../controllers/items');
echo 'debug 1.6';
$model = $this->Inventory_negative_stock;
var_dump($model);
$tabular_data = array();
$edit_file = 'items/view/';
$width = $this->items->get_form_width();
echo 'debug 1.7';
$report_data = $model->getData(array());
echo 'debug 1.8';
foreach($report_data as $row)
{
// set up the item_number to handle blanks
if ($row['item_number'] == NULL) {$row['item_number'] = $this->lang->line('common_edit');}
// load each line to the output array
$tabular_data[] = array(
$row['category'],
anchor (
$edit_file.$row['item_id'].'/width:'.$width,
$row['item_number'],
array('class'=>'thickbox','title'=>$this->lang->line('items_update'))
),
$row['name'],
$row['cost_price'],
$row['quantity']
);
}
// load data array for display
$today_date = date('d/m/Y; H:i:s', time());
$data = array (
"title" => $this->lang->line('reports_negative_stock'),
"subtitle" => ' - '.$today_date.' '.$this->lang->line('common_for').' '.$this->db->database.'.',
"headers" => $model->getDataColumns(),
"data" => $tabular_data,
"summary_data" => $model->getSummaryData(array()),
"export_excel" => $export_excel
);
if ($export_excel == 1)
{
$this->load->model('Common_routines');
$this->Common_routines->create_csv($data);
}
else
{
$this->load->view("reports/tabular", $data);
}
return;
}
This line is failing
$model=$this->Inventory_negative_stock;
In the first function $model is loaded correctly. In the second it isn't.
It does not matter in which order these functions are called; $model always fails to load in the second function called.
Any help would be great and thanks in advance. I hope I've given enough code; if you need more information let me know.
As requested, here is the code in Inventory_negative_stock,
<?php
require_once("report.php");
class Inventory_negative_stock extends Report
{
function __construct()
{
parent::__construct();
}
public function getDataColumns()
{
return array (
$this->lang->line('reports_category'),
$this->lang->line('reports_item_number'),
$this->lang->line('reports_item_name'),
$this->lang->line('reports_cost_price'),
$this->lang->line('reports_count')
);
}
public function getData(array $inputs)
{
$this->db->select('category, name, cost_price, quantity, reorder_level, reorder_quantity, item_id, item_number');
$this->db->from('items');
$this->db->where("quantity < 0 and deleted = 0");
$this->db->order_by('category, name');
return $this->db->get()->result_array();
}
public function getSummaryData(array $inputs)
{
return array();
}
}
?>

Codeigniter Data Passing

Controller Name: mother.php
Controller Function:
public function mother_dram_print() {
$mother = array();
$mother['label'] = $this->load->view('mother/mother_dram', '', TRUE);
$data = array(
'name_1' => $this->input->post('name_1'),
'size_1' => $this->input->post('size_1'),
'qty_1' => $this->input->post('qty_1')
);
$data['label_print'] = $this->load->view('print_template', $mother, TRUE);
$this->load->view('home', $data);
}
View File Name: mother_dram.php
View File:
<div class="moth-dram-label-main-container fix">
<?php
for ($p1 = 1; $p1 <= $qty_1; $p1++) {
echo "<div class='moth-dram-label-wrapper fix'>";
echo "<div class='moth-dram-name fix'>$name_1</div>";
echo "<div class='moth-dram-ml'>$size_1</div>";
echo "</div>";
}
</div>
Note: when I am submitted data from html form data can't view in mother_dram.php file.
Define your $data before you pass it into $this->load->view('mother/mother_dram', $data, TRUE);
From the style of your code, it looks like you think that $data is passed along views as long as you define it somewhere, but this isn't the case.

Cant pass array value from codeigniter controller to view

Inside my controller, I have a line that needs to pass $content['pass_check'] to the view. It is inside an if statement that checks for validation. This I have found causes it to break. Once I move the $content['pass_check'] outside of any if statement, it works just fine passing to the view. All of the other values are passed (accounts, expense_accounts, vendors, terms). What must I do to get it to pass within this if statement. I've even tried moving it outside of the validation and it still wont set.
function create() {
require_permission("INVOICE_EDIT");
$this->load->library("form_validation");
$this->form_validation->set_rules("invoice_number", "Invoice Number", "required");
if($this->form_validation->run() !== false) {
$post = $this->input->post();
$this->session->set_userdata("create_invoice_vendor", $post['vendor_id']);
$this->session->set_userdata("create_invoice_date", $post['invoice_date']);
$invoice_number_exists = $this->invoices->count(array("invoice_number" => $post['invoice_number'])) > 0;
$post['invoice_date'] = date("Y-m-d", strtotime($post['invoice_date']));
$post['due_date'] = date("Y-m-d", strtotime($post['due_date']));
$post['date_entered'] = "now()";
$id = $this->invoices->insert_invoice($post);
$this->load->model("vendors");
if(isset($post['invoice_number'])){
$string_check= $post['invoice_number'];
$string_check= preg_replace('/\d/', '#', $string_check);
$string_check= preg_replace('/\w/', '#', $string_check);
$invoice_pattern=array();
$invoice_pattern = $this->db->select("invoice_pattern")->where("vendor_id",
$post['vendor_id'])->get("vendors")->result();
$invoice_pattern=$invoice_pattern[0]->invoice_pattern;
* //// THIS IS WHERE I NEED HELP ///////
if($invoice_pattern == $string_check){
***$content['post_check'] = 1;***
$this->invoices->flag_invoice($id);
};
};
$history = array(
"type" => "invoice_entered",
"comments" => "Invoice was entered",
"link" => $id,
"admin_id" => $this->user->admin_id,
"date" => "now()",
);
$this->vendors->insert_history($post['vendor_id'], $history);
if($post['flagged'] == 1) {
$this->invoices->flag_invoice($id);
}
if($invoice_number_exists) {
redirect("invoices/confirm_invoice/".$id);
} else {
// redirect("invoices/view/".$id);
redirect("invoices/create");
}
}
$content['accounts'] = $this->db->get("acct_chart_of_accounts")->result();
$content['expense_accounts'] = $this->db->get("invoice_expense_accounts")->result();
$content['vendors'] = $this->db->select("vendor_id, name, terms, override, invoice_pattern")
->order_by("name ASC")->get("vendors")->result();
$content['terms'] = $this->db->query("SELECT DISTINCT(terms) FROM vendors")->result();
}
}
$this->template['sub_heading'] = "Create";
$this->template['content'] = $this->load->view("invoices/create", $content, true);
$this->template['sidebar'] = $this->load->view("invoices/sidebar", array(), true);
$this->template['scripts'] = array("codeigniter/javascript/invoices/create.js");
$this->template['styles'][] = "codeigniter/styles/invoices/create.css";
$this->display();
}
Obviously it won't pass it to the view if the condition doesn't match, because you're only declaring the variable within the condition if it matches.
Just create $content['pass_check'] with an initial value of 0 or whatever before the conditional check first.
function create() {
...snip...
$content['pass_check'] = 0;
if($invoice_pattern == $string_check) {
$content['post_check'] = 1;
$this->invoices->flag_invoice($id);
};
...snip...
}
Let me know if this works or not please.

Eval'ing Plugins System

What would be the best way to do this?
I'm given a template with some things in it like {:HELLO-WORLD:} tags in it.
I'm also given an array like:
Array
(
[0] => Array
(
[Name] => {:HELLO-WORLD:}
[Plugin] => "<?php return 'Hello World'; ?>"
[Settings] =>
)
)
What can I do to make sure {:HELLO-WORLD:} gets replaced with the output of Hello World?
I am currently attempting:
private function PluginReplacer($arr, $str){
$gsCt = count($arr);
$kv = array();
for ($i=0;$i<$gsCt;++$i){
$kv[$arr[$i]['Name']] = $arr[$i]['Plugin'];
}
return str_replace(array_keys($kv), $this->EvalCode(array_values($kv)), $str);
}
// Eval Some Code
private function EvalCode($var){
require_once('plugins.php');
$pr = new CloudCMSPluginRunner();
$pr->Code = $var;
$pr->SitePath = GetSiteAssetsPath($this->SiteID);
$pr->RunIt();
echo $pr->Error;
}
<?php
class CloudCMSPluginRunner {
public $Code = '';
public $Error = '';
public $SitePath = '';
private $DoNotAllow = array('echo', 'eval', 'phpinfo', '/`/', 'chmod', 'chown', 'umask', 'shell_exec',
'exec', 'escapeshellcmd', 'proc_open', 'proc_terminate', 'proc_get_status',
'passthru', 'proc_nice', 'system', 'escapeshellarg', 'ob_start', 'ob_end_clean',
'ob_get_clean', 'session_start', 'putenv', 'header', 'sleep', 'uwait', 'ini_set',
'error_reporting', 'chgrp', 'basename', 'clearstatcache', 'copy', 'delete',
'dirname', 'disk_free_space', 'disk_total_space', 'diskfreespace', 'fclose',
'feof', 'fflush', 'fgetc', 'fgetcsv', 'fgets', 'fgetss', 'file_exists', 'file_get_contents',
'file_put_contents', 'file', 'fileatime', 'filectime', 'filegroup', 'fileinode', 'filemtime',
'fileowner', 'fileperms', 'filesize', 'filetype', 'flock', 'fnmatch', 'fopen', 'fpassthru',
'fputcsv', 'fputs', 'fread', 'fscanf', 'fseek', 'fstat', 'ftell', 'ftruncate', 'fwrite', 'glob',
'is_dir', 'is_executable', 'is_file', 'is_link', 'is_readable', 'is_uploaded_file', 'is_writeable',
'is_writable', 'lchgrp', 'lchown', 'link', 'linkinfo', 'lstat', 'mkdir', 'move_uploaded_file',
'parse_ini_file', 'parse_ini_string', 'pathinfo', 'pclose', 'popen', 'readfile', 'readlink',
'realpath_cache_get', 'realpath_cache_size', 'realpath', 'rename', 'rewind', 'rmdir', 'set_file_buffer',
'stat', 'symlink', 'tempnam', 'tmpfile', 'touch', 'unlink', 'chdir', 'chroot', 'closedir', 'dir',
'getcwd', 'opendir', 'readdir', 'rewinddir', 'scandir', 'dio_close', 'dio_fcntl', 'dio_open', 'dio_read',
'dio_seek', 'dio_stat', 'dio_tcsetattr', 'dio_truncate', 'dio_write', 'finfo_buffer', 'finfo_close',
'finfo_file', 'finfo_open', 'finfo_set_flags', 'mime_content_type', 'inotify_add_watch', 'inotify_init',
'inotify_queue_len', 'inotify_read', 'inotify_rm_watch', 'setproctitle', 'setthreadtitle', 'xattr_get',
'xattr_list', 'xattr_remove', 'xattr_set', 'xattr_supported');
public function RunIt(){
$valid = $this->CheckIt();
if($valid){
eval($this->Code);
}else{
// code is invalid
$this->Error = 'The code in this plugin is invalid.';
return null;
}
}
private function CheckIt(){
$ret = false;
ob_start(); // Catch potential parse error messages
$code = eval('if(0){' . "\n" . $this->Code . "\n" . '}');
ob_end_clean();
$ret = ($code !== false);
// run a check against the dissallowed
$ret = (stripos($this->Code , $this->DoNotAllow) !== false);
// make sure any path is there's and there's alone
$ret = (stripos($this->Code , $this->SitePath) !== false);
return $ret;
}
}
?>
But nothing is happenning... in fact the page I am attempting to run this on blanks out (meaning there is an error happenning)
You're generating code formatted as:
eval("function GetPageWeAreOn(){$p=explode('/',$_SERVER['REQUEST_URI']);return $p[1];}");
What's happening is that PHP is interpreting the variables wrongly - instead of passing them in to the eval'ed function, it's interpolating them first.
I've avoided the error by escaping them:
eval("function GetPageWeAreOn(){\$p=explode('/',\$_SERVER['REQUEST_URI']);return \$p[1];}");
You can avoid the need for escaping by putting your string to be eval'ed into single quotes, too - that doesn't try to interpolate variables:
eval('function GetPageWeAreOn(){$p=explode("/",$_SERVER["REQUEST_URI"]);return $p[1];}');

Categories