How to combine two SQL tables in codeigniter without using SQL queries? - php

Here is my codes,
//FROM MY CONTROLLER
$companies = $this->Uploads_model->getallcompanies();
$general = $this->Uploads_model->getallcontract();
$this->data['companieslist'] = $companies;
$this->data['uploads'] = $general;
$this->render('contracts/index_view');
// MY VIEW
foreach($companieslist as $company){
$general_c[] = $company->company_id;
$general_c[] = $company->company_name;
}
foreach ( $uploads as $key => $con ) {
?>
<tr>
<td class="center">
<label class="pos-rel">
<input type="checkbox" class="ace"/>
<span class="lbl"></span>
</label>
</td>
<td>
<a href="#">
<?php
if($con->Company_id == $general_c[$company_id]){ // MY QUESTION IS HERE
echo $con->Company_name;
}
?>
</a>
</td>
So, am working on this web app where am supposed to display in table all contract files followed with company owned this contract.
I have two tables in my Database as follow Companies_tbl and contract_tbl.
I have Company_id as a foreign key in contract_tbl.

Create a custom function to filter your contracts based on Company_id
function getContractsForId($contracts,$Company_id) {
return array_filter($contracts,function(){
return $contracts->Company_id === $Company_id;
});
}
template loop:
foreach( getContractsForId($uploads,$Company_id) as $key => $con) {
//...html...
//remove the if
}

You are not building the array of companies the right way.
foreach($companieslist as $company){
$general_c[] = $company->company_id;
$general_c[] = $company->company_name;
}
After you looped once, the $general_c array will look like this:
$general_c = [
0 => 1, //company id
1 => 'Company name'
]
After the second time:
$general_c = [
0 => 1, //company id
1 => 'Company name',
2 => 2, //company id
3 => 'Company name 2'
]
What you want is the following:
foreach($companieslist as $company){
$general_c[$company->company_id] = $company->company_name;
}
And below:
<?php
if($general_c[$con->Company_id]) {
echo $general_c[$con->Company_id];
} ?>
This will let you output the company name based on ID.
But i suggest you do a MySQL join in your model. Add something like this to your Uploads_model:
function getContractsWithCompany() {
$query = $this->db->select('*')
->from('contract_tbl')
->join('Companies_tbl', 'Companies_tbl.id = contract_tbl.Company_id')
->get();
return $query->result();
}

You need first to group files by Company_id then list the specific company files
$companies = $this->Uploads_model->getallcompanies();
$general = $this->Uploads_model->getallcontract();
$this->data['companieslist'] = $companies;
$this->data['uploads'] = array();
//group file list by Company_id
foreach ($general as $key => $file) {
if(!isset($this->data['uploads'][$file->Company_id ]))
$this->data['uploads'][$file->Company_id] = array();
$this->data['uploads'][$file->Company_id][] = $file;
}
// in your view
foreach($companieslist as $company){
$general_c[] = $company->company_id;
$general_c[] = $company->company_name;
if(isset($uploads[$company->company_id])) {
foreach ( $uploads[$company->company_id] as $key => $con ) {
?>
<tr>
<td class="center">
<label class="pos-rel">
<input type="checkbox" class="ace"/>
<span class="lbl"></span>
</label>
</td>
<td>
<?=$company->company_name?>
</td>
</tr>
<!-- and the rest of logic -->
<?php
}
}
}

Related

how to update multiple value in codeigniter

I have input data that I will fill with different values, I do multiple updates
but I have an error which is:
Unknown column 'Array' in 'field list' UPDATE service SET
charges_order = WHERE array id_service = '1'
how to overcome this?
example img
View
<?php $no = 1; foreach ($invoice as $m) { ?>
<tbody id="tbody">
<form class="form-signin" method="post" action="<?php echo base_url();?>backend/report/update/<?php echo $m->id_service; ?>">
<tr class="deleted">
<td><input type="text" class="form-control" name="charges_order[]" value="<?php echo $m->charges_order;?>"></td>
</tr>
</form>
</tbody>
<div class="box-footer">
<button type="submit" class="btn bg-blue btns-flat margin">Simpan</button>
</div>
<?php } ?>
Controller
public function update($id_service)
{
foreach ($this->input->post('charges_order') as $data) {
$data = array(
'charges_order' => $this->input->post('charges_order')
);
// echo '<pre>', print_r($data);
$this->M_report->update($id_service, $data);
redirect('backend/report');
}
}
Model
public function update($id_service, $data)
{
$this->db->where('id_service', $id_service);
$this->db->update('service', $data);
}
Change your controller to this-
public function update($id_service){
$charges_order = json_encode($this->input->post('charges_order'));
$data = array(
'charges_order' => $charges_order
);
$this->M_report->update($id_service, $data);
redirect('backend/report');
}
This should work for you.
You are in a loop. You must use the variable.
$data = array(
'charges_order' => $data
);
You can convert array into a string and then update the table.
//example
[1,2,3,4] -> "1,2,3,4"
Here is the code
public function update($id_service)
{
$data = array(
'charges_order' => implode(",", $_POST['charges_order'])
);
// echo '<pre>', print_r($data);
$this->M_report->update($id_service, $data);
redirect('backend/report');
}
When you are retrieving, you can reverse the process
public function get_orders($id_service)
{
$this->db->select('charges_order');
$this->db->where('id_service', $id_service);
$result = $this->db->get('service')->result_array();
return explode(",", $result["charges_order"]); //returns an array
}

How to update database base on laravel checkbox value

I load check boxes from database with they are checked or not,
<div class="row">
<div class="col-xs-12">
<div class="form-group">
#php
$json = $orders->data;
$json = json_decode($json, true);
$products = $json['order_info']['products'];
$data = '';
foreach ($products as $hitsIndex => $hitsValue) {
$data .= $hitsValue['type']. ', ';
}
$data = rtrim($data, ', ');
$agosProducts = Utility::constant('agos_products1');
#endphp
{{Html::validation($orders, 'product')}}
<label for="products" class="control-label">{{Translator::transSmart('app.Products', 'Products')}}</label><br><br>
#foreach($agosProducts as $product)
<label class="control-label "for="{{ $product['type'] }}">
<input id="{{ $product['type'] }}" name="{{ $product['type'] }}" type="checkbox" value="{{ $product['type'] }}"
#foreach ($products as $hitsIndex => $hitsValue)
#if(in_array($hitsValue['type'], $product)) checked=checked #endif
#endforeach
>
{{ $product['name'] }}
</label>
<br>
#endforeach
</div>
</div>
</div>
Now i want to update my database base on checkbox value.
For example if say i load checkbox 1 as checked from database and now it's unchecked i need to update it in database.
This code i can get all the current status of checkbox but i don't know previous values of this. So it hard update statue of current values and add new status in database,
$chks = array('multicolor','resizable','showRuler','namesNumbersEnabled');
foreach ($chks as $chk) {
$product->setAttribute($chk, (Input::has($chk)) ? true : false);
}
This is my json object save in data column
{"user_token":"ad48c412-3866-4ac9-adf6-3328911ae46c",
"order_info":
{"order_id":"CGC12345678","company_id":32,"price":1000.5,"currency":"MYR",
"products":[
{"type":"HR_ECLAIM","name":"HREClaim","is_fixed_price":true,"price":500.5,"currency":"MYR"},
{"type":"HR_ELEAVE","name":"HRELeave","is_fixed_price":true,"price":500,"currency":"MYR"}
],
"total_invoices":200,"total_staffs":80},"url":"https://drive.google.com/open?id=1Is6QsnuMLu9ZIpqeEzR2O2Ve1wUyF92aVCg55kWsOgc"}
i load [order_info][products][type] as checked products in while i load all the products from env file. I only need to save checked check box products in db.
Can someone helps me?
This is the complete working solution i done for my question!
public function edit($id, $attributes){
$orders = (new Agos())->load($id);
$json = $orders->data;
$json = json_decode($json);
$checkedit= $attributes['check_list'];
if (is_array($checkedit) || is_object($checkedit))
{
foreach($checkedit as $chked1){
$exists = false;
foreach($json->products as $key => $val)
{
// update if products exists
if($val->type == $chked1) {
$val->status = 'true';
$exists = true;
}
if(array_key_exists('status', $val)) {}
else{ $val->status = 'false';}
}
if($chked1 == 'FIN_REPORTING')
{
$name = 'Finance reporting & book keeping';
}
elseif ($chked1 == 'FIN_ADVISORY')
{
$name = 'Finance Advisory';
}
elseif ($chked1 == 'PAYROLL_HRDB')
{
$name = 'PAYROLL_HRDB';
}
elseif ($chked1 == 'HR_ELEAVE')
{
$name = 'HR E-Leave';
}
else
{
$name = 'HR E-Claim';
}
//if products not exists add new products
if(!$exists) {
$newproduct = new \stdClass();
$newproduct->type = $chked1;
$newproduct->name = $name;
$newproduct->is_fixed_price = false;
$newproduct->currency = "MYR";
$newproduct->status = "true";
array_push($json->products, $newproduct);
}
}
}
//remove all products that have status = false
foreach($json->products as $index => $product) {
if ( $product->status == "false") {
unset($json->products[$index]);
}
}
$json->products = array_values($json->products);
json_encode($json, JSON_PRETTY_PRINT);
//remove status element from products
foreach($json->products as $index => $product) {
unset($product->status);
}
$json->products = array_values($json->products);
json_encode($json, JSON_PRETTY_PRINT);
$json->google_drive_url= $attributes['data'];
$json->remark= $attributes['remark'];
$json->status= $attributes['status'];
$json->total_invoices= $attributes['total_invoices'];
$json->total_staffs= $attributes['total_staffs'];
$json1 = json_encode($json);
$status = $attributes['status'];
$total_price = str_replace(',','', $attributes['total_price']);
DB::table('orders')
->where('id', $id)
->update(['data' => $json1,'status' => $status, 'price' => $total_price]);
}

cakephp 2.9.7 data validation is not working

The problem is very simple but why it is complicating for me.I have written data validation also.But for empty fields also it is accepting the input.please check whether any error in my action.php.
Model/action.php
<?php
App::uses('AppModel', 'Model');
class Actions extends AppModel {
public $validate = array(
'value_to_plot' => array(
'required'=>true,
'message' => 'atleast select one measure'
),
'column_name' => array(
'required'=>true,
'rule'=>array('notBlank'),
'message' => 'atleast select one table'
)
);
}
?>
View/Actions/index.ctp
<div align="center">
<fieldset>
<?php echo $this->Form->create('valueToSend',array('type' => 'get'));?>
<?php if(isset($_GET['table_name'])){ ?>
<table class="table table-bordered table-hover table-striped">
<?php echo $this->Form->hidden('table_name', array('hiddenField' => true, 'value'=> $_GET['table_name'],'id'=>'table_name'));
echo $this->Form->hidden('chart', array('hiddenField' => true, 'value'=> "column3d",'id'=>"chart"));
?>
<tr>
<th>MEASURES</th>
<td>
<?php echo $this->Form->select('value_to_plot',$measures1,array('class'=>'form-control','id'=>'measures','required'=>true),['empty' => 'choose one']);?>
</td>
</tr>
<tr>
<th>DIMENSIONS</th>
<td>
<?php echo $this->Form->select('column_name[]',$measures2,array('multiple'=>'true','class'=>'form-control','id'=>'dimensions','required'=>true),['empty' =>'choose one']);?>
</td>
</tr>
</table>
<div style="text-align:center">
<?php echo $this->Form->end('submit'); ?>
</div>
<?php } ?>
</fieldset>
</div>
Controller/ActionsController.php
<?php
App::uses('AppController', 'Controller');
class ActionsController extends AppController {
public function beforeFilter() {
if(!isset($_SESSION['Auth']) && empty($_SESSION['Auth'])) {
$userId = $_SESSION['Auth[User[id]]'];
return $this->redirect(array('controller' => 'Users', 'action' => 'login'));
}
}
public Function index(){
App::import('Model', 'ConnectionManager');
$con = new ConnectionManager;
$cn = $con->getDataSource('default');
$tablequery="SELECT TABLE_NAME as table_name
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA='phygital_visualize' AND TABLE_NAME != 'report'";
$rows = $cn->query($tablequery);
//$rows = $result->fetchAll('assoc');
$dataToTable = [];
foreach ($rows as $row) {
$dataToTable[$row['TABLES']['table_name']] = $row['TABLES']['table_name'];
}
$this->set('table',$dataToTable);
if(isset($_GET['table_name'])){
$table_name = $_GET['table_name'];
$column = "select column_name as name from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='$table_name' ";
$result = $cn->query($column) ;
foreach ($result as $key => $value) {
foreach($value as $key => $value) {
foreach($value as $key =>$value){
$column_counts[$value] = $value;
}
}
}
$column_counts = array_unique($column_counts);
//print_r($column_counts);
$measures1=array();
$measures2=array();
$diff=array();
foreach($column_counts as $key => $value){
$sql="select * from $table_name where concat('',$value * 1 ) = $value limit 1";
$resultset = $cn->query($sql) ;
if(!empty($resultset)){
if(!in_array($value, $measures1)){
$measures1[$value]= $value;
}
}
}
$measures2 = array_diff($column_counts,$measures1);
$this->set('measures1',$measures1);
$this->set('measures2',$measures2);
}
}
}
?>
This will validate and save your data
if ($this->request->is('post')) {
$this->Actions->set($this->request->data);
if ($this->Actions->save($this->request->data)) {
// Set a session flash message and redirect.
}
}
I think you're confusing "'required'=>true" with "'allowEmpty' => true". The former means that you cannot save the record without that field being included in the list of fields updated, no matter whether it holds actual data or not. The latter, which I think is what you really mean, allows a field to be empty although it doesn't force a declaration.

How to display information from my database to html table?

Currently I'm trying to display all the payments I have received that were inserted into my database (payment_history) I want to show them in a html table, but every time I try it, It only shows me 1 user on the html table, but I have more than one user in the SQL table on phpmyadmin.
Php sided code.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class payment_history_model extends MY_Model {
public function __construct(){
parent::__construct();
}
public function getPaymentHistory(){
$accounts = $this->model->fetch("*", PAYMENT_HISTORY, getDatabyUser(0), "id", "asc");
if(!empty($accounts)){
foreach ($accounts as $key => $row) {
$user = $this->model->get("*", USER_MANAGEMENT, "id = '".$row->uid."'");
if(!empty($user)){
$accounts[$key]->user = $user->fullname;
}else{
$accounts[$key]->user = "";
}
}
}
return $accounts;
}
}
My html table code.
<thead>
<tr>
<th><?=l('User')?></th>
<th><?=l('Invoice')?></th>
<th><?=l('First name')?></th>
<th><?=l('Last name')?></th>
<th><?=l('Receiver email')?></th>
<th><?=l('Payer email')?></th>
<th><?=l('Package')?></th>
<th><?=l('Price')?></th>
<th><?=l('Currency')?></th>
<th><?=l('Street')?></th>
<th><?=l('City')?></th>
<th><?=l('Country')?></th>
<th><?=l('Payment date')?></th>
<th><?=l('Payment status')?></th>
<th><?=l('Option')?></th>
</tr>
</thead>
<tbody>
<?php
if(!empty($result)){
foreach ($result as $key => $row) {
?>
<tr class="pending" data-action="<?=cn('ajax_action_item')?>" data-id="<?=$row->id?>">
<td>
<input type="checkbox" name="id[]" id="md_checkbox_<?=$key?>" class="filled-in chk-col-red checkItem" value="<?=$row->id?>">
<label class="p0 m0" for="md_checkbox_<?=$key?>"> </label>
</td>
<td><?=$row->user?></td>
<td><?=$row->invoice?></td>
<td><?=$row->first_name?></td>
<td><?=$row->last_name?></td>
<td><?=$row->receiver_email?></td>
<td><?=$row->payer_email?></td>
<td><?=$row->item_name?></td>
<td><?=$row->mc_gross?></td>
<td><?=$row->mc_currency?></td>
<td><?=$row->address_street?></td>
<td><?=$row->address_city?></td>
<td><?=$row->address_country?></td>
<td><?=$row->payment_date?></td>
<td><?=$row->payment_status?></td>
<td><?=$row->Option?></td>
</tr>
</tbody>
Ok, your class MyModel from http://pastebin.com/Vc8tUvpH contains fetch method:
function fetch($select = "*", $table = "", $where = "", $order = "", $by = "DESC", $start = -1, $limit = 0, $return_array = false)
{
...
}
Now, we can say that the problem can be in $where = getDatabyUser(0).
Most likely getDatabyUser(0) adds where clause which limits your result to one row.
You should try:
output getDatabyUser(0) like var_dump(getDatabyUser(0))
open phpmyadmin and add the same where clause and check result
Now it looks like you're trying to get payment history for user with ID = 0.
You can check it also, by replacing getDatabyUser(0) with ""(empty string).
public function getPaymentHistory(){
$accounts = $this->model->fetch("*", PAYMENT_HISTORY, "", "id", "asc");
if(!empty($accounts)){
foreach ($accounts as $key => $row) {
$user = $this->model->get("*", USER_MANAGEMENT, "id = '".$row->uid."'");
if(!empty($user)){
$accounts[$key]->user = $user->fullname;
}else{
$accounts[$key]->user = "";
}
}
}
return $accounts;
}

Looping in array (php codeigniter)

The problem is looping in $t array on controller page
Any Solution?
Here's my code
Controller:
function save($id)
{
$i=0;
$t = array(
for($i;$i<=34;$i++)
'j'.$i => $this->input->post('j'.$i),
'status' => $this->input->post('1')
);
$this->mmeeting->save($id,$t);
redirect('admin/meeting','refresh');
}
Model:
function save($t){
$this->db->insert("meeting", $t);
return $this->db->insert_id();
}
View:
<?
$i=1;
foreach ($im as $row):
$i++;
?>
<input name="j.<? echo $i; ?>" type="hidden" value="<? echo $row['when'] ?">>
<? endforeach; ?>
<input type="submit" value="register" tabindex="7" />
Meeting table in database
CREATE TABLE IF NOT EXISTS `meeting`
(
`j1` date ,
`j2` date ,
....
`j34` date ,
status int(1),
)ENGINE=InnoDB DEFAULT CHARSET=armscii8;
This has nothing to do with codeigniter, just php. The following is not valid:
$t = array(
for($i;$i<=34;$i++)
'j'.$i => $this->input->post('j'.$i),
'status' => $this->input->post('1')
);
Use this instead:
$t = array('status' => $this->input->post('1'));
for ($i; $i <= 34; $i++) {
$t["j$i"] = $this->input->post("j$i");
}
If i understood correctly what you want
function save($id)
{
$i=0;
$t = array();
for($i;$i<=34;$i++)
$t["j$i"] = $this->input->post("j$i");
$t['status'] => $this->input->post('1');
$this->mmeeting->save($id,$t);
redirect('admin/meeting','refresh');
}

Categories