How to display information from my database to html table? - php

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;
}

Related

"Message : Undefined Variable:query " error on joining two tables codeigniter mysql php

I have two tables named 'addexpense' and 'addcategory' .
I have successfully joined each of the tables but on my view page the data are not viewing and an error message is passed on the screen. Please help.
This is my model
public function getExpenses(){
$this->db->select("addexpense.exp_date, addexpense.exp_amount, addexpense.exp_note, addexpense.exp_created, addcategory.category_name");
$this->db->from('addexpense');
$this->db->join('addcategory', 'addcategory.category_id = addexpense.category_id');
$query = $this->db->get();
return $query->result();
}
This is my Controller
public function join(){
$query = $this->base_model->getExpenses();
//$data['result'] = null;
if($query)
{
$data['query'] = $query;
}
$this->load->view('listexpense', $data);
}
This is my view code
<tr>
<td><strong>Date</strong></td>
<td><strong>Amount</strong></td>
<td><strong>Note</strong></td>
<td><strong>Created</strong></td>
<td><strong>Category Name</strong></td>
</tr>
<?php foreach($query as $expenses){?>
<tr>
<td><?=$expenses->exp_date;?></td>
<td><?=$expenses->exp_amount;?></td>
<td><?=$expenses->exp_note;?></td>
<td><?=$expenses->exp_created;?></td>
<td><?=$expenses->category_name;?></td>
</tr>
<?php }?>
set controller function this way
public function join(){
$data['query'] = $this->base_model->getExpenses();
$this->load->view('listexpense', $data);
}
Please can you check your data is going on view file or not by printing it at start of your view
<?php echo '<pre>';
print_r($query);
?>
It seems like you have not initialized model in controller.
In your controller you need to load model first before using its properties. Please check below for your controller method.
public function join() {
$this->load->model('base_model');
$query = $this->base_model->getExpenses();
$data = array();
if ($query) {
$data['query'] = $query;
}
$this->load->view('listexpense', $data);
}
Let me know still it not works.
Model change result() to result_array()
public function getExpenses(){
$this->db->select("addexpense.exp_date, addexpense.exp_amount, addexpense.exp_note, addexpense.exp_created, addcategory.category_name");
$this->db->from('addexpense');
$this->db->join('addcategory', 'addcategory.category_id = addexpense.category_id');
$query = $this->db->get();
return $query->result_array();
}
Controller try code below
public function join()
{
$results = $this->base_model->getExpenses();
$data['expenses'] = array();
foreach ($results as $result) {
$data['expenses'][] = array(
'exp_date' => $result['exp_date'],
'exp_amount' => $result['exp_amount'],
'exp_note' => $result['exp_note'],
'exp_created' => $result['exp_created'],
'category_name' => $result['category_name']
);
}
$this->load->view('listexpense', $data);
}
View make sure is the correct view
<table>
<thead>
</thead>
<tbody>
<?php foreach($expenses as $expense){?>
<tr>
<td><?php echo $expense['exp_date'];?></td>
<td><?php echo $expense['exp_amount'];?></td>
<td><?php echo $expense['exp_note'];?></td>
<td><?php echo $expense['exp_created'];?></td>
<td><?php echo $expense['category_name'];?></td>
</tr>
<?php }?>
</tbody>
</table>
Here is the code please check and update
Model
public function getExpenses(){
$this->db->select("addexpense.exp_date, addexpense.exp_amount, addexpense.exp_note, addexpense.exp_created, addcategory.category_name");
$this->db->from('addexpense');
$this->db->join('addcategory', 'addcategory.category_id = addexpense.category_id');
$query = $this->db->get();
$query_rows = $query->num_rows();
if($query_rows > 0){
return $query->result();
} else{
return 0;
}
}
For Controller
public function join(){
$this->load->model('base_model');
$query = $this->base_model->getExpenses();
//print_r($query);die();
$data['query'] = '';
if($query != 0){
$data['query'] = $query;
}
$this->load->view('listexpense', $data);
}
For View
<tr>
<td><strong>Date</strong></td>
<td><strong>Amount</strong></td>
<td><strong>Note</strong></td>
<td><strong>Created</strong></td>
<td><strong>Category Name</strong></td>
</tr>
<?php
if($query != ''){
foreach($query as $expenses){?>
<tr>
<td><?=$expenses->exp_date;?></td>
<td><?=$expenses->exp_amount;?></td>
<td><?=$expenses->exp_note;?></td>
<td><?=$expenses->exp_created;?></td>
<td><?=$expenses->category_name;?></td>
</tr>
<?php } }?>
remove the comment "//print_r($query);die();" and check that whether the model is sending the data or not and please update..

SQL Query with specific ID/row on Codeigniter

I need to print my data with specific ID by using SELECT * FROM query and I have problem with my query.
Example, i have table called tb_pasien , and it has 8 columns :
kode_pasien(as ID), nama_pasien, email_pasien, alamat_pasien, tanggal_lahir, umur, jenis_kelamin and no_telp.
So, when I want to print someone data it will only show her/his data not all data on my table.
This is my code :
Model
public function view_kartu()
{
$query = $this->db->query("SELECT * FROM tb_pasien where kode_pasien='$kode_pasien' LIMIT 1");
return $query;
}
Controller
public function cetakkartu() {
// Load all views as normal
$data['pasien'] = $this->a_model->view_kartu();
$this->load->view('cetak-kartu', $data);
// Get output html
$html = $this->output->get_output();
// Load library
$this->load->library('dompdf_gen');
// Convert to PDF
$this->dompdf->load_html($html);
$this->dompdf->render();
$this->dompdf->stream("cetak-kartu" . ".pdf", array ('Attachment' => 0));
}
View
<table border="1" width="100%">
<tr>
<th>Kode Pasien</th>
<th>Nama Pasien</th>
<th>Email Pasien</th>
<th>Alamat Pasien</th>
<th>Tanggal Lahir</th>
<th>Umur</th>
<th>JK</th>
<th>No. Telp</th>
</tr>
<?php
if( ! empty($pasien)){
foreach($pasien as $data){
echo "<tr>";
echo "<td>".$data->kode_pasien."</td>";
echo "<td>".$data->nama_pasien."</td>";
echo "<td>".$data->email_pasien."</td>";
echo "<td>".$data->alamat_pasien."</td>";
echo "<td>".$data->tanggal_lahir."</td>";
echo "<td>".$data->umur."</td>";
echo "<td>".$data->kode_jk."</td>";
echo "<td>".$data->no_telp."</td>";
echo "</tr>";
}
}
?>
</table>
But when i try to print it, it shows empty result. Can someone help me? Thankyou.
Need to the return result array or row but not query (as per your requirement of fetching data from array or array object)
Like this
return $query->result_array();
or
return $query->row();
Try changing your model function as below -
public function view_kartu($kode_paisen)
{
$query = $this->db->query("SELECT * FROM tb_pasien where kode_pasien='$kode_pasien' LIMIT 1");
return $query;
}
And then from your controller, call it as -
public function cetakkartu() {
//set a value for $kode_paisen
$kode_paisen = "XXX"; //set here whatever you like.
// Load all views as normal . See here we passing the variabke in the function.
$data['pasien'] = $this->a_model->view_kartu($kode_paisen);
// Rest of your function ...
}
As an example, i have a table "currency" in my site and this is how i fetch all the currencies mapped to a particular company in Code Igniter model.
function getCurrencyList($companyId)
{
$sql = "select currency_id from company_currency where company_id = $companyId";
$retVal = $this->db->query($sql);
if($this->db->affected_rows() == 0)
{
return null;
}
if($retVal && $this->db->affected_rows() > -1)
{
if($retVal->result_array())
{
foreach($retVal->result_array() as $row)
{
$arrCurrencyId[] = $row['currency_id'];
}
}
return $arrCurrencyId;
}
else
{
log_message('error', mysql_error()." ******* at function getActionList Role Model *********");
return null;
}
}
I hope this will help you
try this query:
$this->db->select('kode_pasien as ID, nama_pasien, email_pasien, alamat_pasien, tanggal_lahir, umur, jenis_kelamin, no_telp');
$this->db->from('tb_pasien');
$data= $this->db->get()->result_array();
echo "<pre>"; print_r($data);die;

Executing query from Prestashop to external database

I'm trying to connect from Prestashop to external database (ERP) to get the order history from it.
I've cloned the History controller and named it "residui".
I've created ResiduiController.php that contains:
class ResiduiControllerCore extends FrontController {
public $auth = true;
public $php_self = 'residui';
public $authRedirection = 'residui';
public $ssl = true;
public function setMedia() {
parent::setMedia();
$this->addCSS(array(
_THEME_CSS_DIR_.'residui.css',
));
$this->addJS(array(
_THEME_JS_DIR_.'history.js',
_THEME_JS_DIR_.'tools.js' // retro compat themes 1.5
));
$this->addJqueryPlugin('footable');
$this->addJqueryPlugin('footable-sort');
$this->addJqueryPlugin('scrollTo'); }
public function initContent() {
parent::initContent();
$residui = Order::getCustomerResidui($this->context->customer->id);
$this->context->smarty->assign(array(
'residui' => $residui
));
$this->setTemplate(_PS_THEME_DIR_.'residui.tpl'); } }
I've inserted the class getCustomerResidui in Order.php:
public static function getCustomerResidui($id_customer, $showHiddenStatus = false, Context $context = null) {
if (!$context)
$context = Context::getContext();
$evadi = 'S';
$stato = 'GENERATO';
$resi = Db::getFromGazie()->executeS("
SELECT *
FROM "._GAZ_PREFIX_."tesbro
WHERE id_cli_presta = '".(int)$id_customer."' AND status = '".$stato."'
ORDER BY id_tes DESC");
if (!$resi)
return array();
foreach ($resi as $key => $val) {
$resi2 = Db::getFromGazie()->executeS("
SELECT *
FROM "._GAZ_PREFIX_."rigbro
WHERE id_doc = '".$val['numdoc']."' AND evadi <> '".$evadi."'
ORDER BY codart DESC LIMIT 1");
if ($resi2)
$resi[$key] = array_merge($resi[$key], $resi2[0]); }
return $resi; } }
I've added the getFromGazie instance in DB.php and all connection parameters to the external DB in settings.inc.php, such as GAZ_PREFIX, etc.
DB.php:
public static function getFromGazie($master = true) {
static $id = 0;
// This MUST not be declared with the class members because some defines (like _DB_SERVER_) may not exist yet (the constructor can be called directly with params)
if (!self::$_servers)
self::$_servers = array(
array('gaz_server' => _GAZ_SERVER_, 'gaz_user' => _GAZ_USER_, 'gaz_password' => _GAZ_PASSWD_, 'gaz_database' => _GAZ_NAME_), /* MySQL Master server */
);
Db::loadSlaveServers();
$total_servers = count(self::$_servers);
if ($master || $total_servers == 1)
$id_server = 0;
else {
$id++;
$id_server = ($total_servers > 2 && ($id % $total_servers) != 0) ? $id % $total_servers : 1; }
if (!isset(self::$instance[$id_server])) {
$class = Db::getClass();
self::$instance[$id_server] = new $class(
self::$_servers[$id_server]['gaz_server'],
self::$_servers[$id_server]['gaz_user'],
self::$_servers[$id_server]['gaz_password'],
self::$_servers[$id_server]['gaz_database']); }
return self::$instance[$id_server]; }
The template, residui.tpl:
<div class="block-center" id="block-history">
<table id="order-list" class="table table-bordered footab">
<thead>
<tr>
<th class="first_item" data-sort-ignore="true">{l s='Order reference'}</th>
<th class="item">{l s='Date'}</th>
</tr>
</thead>
<tbody>
{foreach from=$residui item=residuo name=myLoop}
<tr class="{if $smarty.foreach.myLoop.first}first_item{elseif $smarty.foreach.myLoop.last}last_item{else}item{/if} {if $smarty.foreach.myLoop.index % 2}alternate_item{/if}">
<td class="history_link bold">
<p class="color-myaccount">
{$residuo['numdoc']}
</p>
</td>
<td class="history_date bold">
{$residuo['datemi']}
</td>
</tr>
{/foreach}
</tbody>
</table>
<div id="block-order-detail" class="unvisible"> </div>
The problem is that I don't get any line displayed (I also tested the query manually in PhpMyAdmin).
I tried for hours but I can't see the mistake (and I'm sure I did one or more).
Can you tell me something? Thanks...
Got it!!!!
First of all thanks to Sergii P that suggests me _PS_MODE_DEV_ that I didn't know...
The problem was that it was always trying to execute the query on the same DB. To solve that, i added _GAZ_NAME_ before _GAZ_PREFIX_, like this:
public static function getCustomerResidui($id_customer, $showHiddenStatus = false, Context $context = null)
{
if (!$context)
$context = Context::getContext();
$evadi = 'S';
$stato = 'GENERATO';
$resi = Db::getFromGazie()->executeS("
SELECT *
FROM "._GAZ_NAME_."."._GAZ_PREFIX_."tesbro
WHERE id_cli_presta = '".(int)$id_customer."' AND status = '".$stato."'
ORDER BY id_tes DESC");
if (!$resi)
return array();
foreach ($resi as $key => $val)
{
$resi2 = Db::getFromGazie()->executeS("
SELECT *
FROM "._GAZ_NAME_."."._GAZ_PREFIX_."rigbro
WHERE id_doc = '".$val['numdoc']."' AND evadi <> '".$evadi."'
ORDER BY codart DESC LIMIT 1");
if ($resi2)
$resi[$key] = array_merge($resi[$key], $resi2[0]);
}
return $resi;
}
Et voilĂ , everything works fine!

DB query is not getting all records as defined

Model
$id = $this->session->userdata('id');
$q = $this->db->get_where('shipping_address', array('customer_id' => $id));
if ($q->num_rows == 0)
{
$data['id'] = 'You dont have a shipping address saved.';
} else {
foreach ($q->result() as $row)
{
$data['first'] = $row->firstname;
$data['last'] = $row->lastname;
}
}
return $data;
Controller
$this->load->model('Customer_accounts');
$customer = $this->Customer_accounts->get_customer_info();
$ship = $this->Customer_accounts->shipping_address();
$data = $ship + $customer;
$this->load->view('account_dashboard/personal_information', $data);
View
<?php foreach ($ship as $row) : ?>
<table class="fixCap" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><?php echo $row['firstname'] . $row['lastname']; ?></td>
</tr>
. . .
</tr>
</table>
<?php endforeach; ?>
Var_dump
Is only showing an array with 1 of the the table rows but it should be showing 2 rows which contain the defined customer_id
Problem
Unable to pass the all the db data to the foreach what am I doing wrong?
use:
$data = array_merge($ship, $customer); // they will merged as one array
or you can do it this way if u want them separated
$data = array();
$data['ship'] = $ship;
$data['customer'] = $customer;
//In the view
//ship
foreach($data['ship'] as $ship)
{
//Ship values
}
//customer
foreach($data['customer'] as $customer)
{
//Customer value
}
thx
You are not actually puling the result from database with your code.
try something like this
$ret = $q->get()->result();
foreach($ret as $row)
{
}
The problem was in my Model I replaced the above code with
Model
return $this->db->get_where('shipping_address', array('customer_id' => $id))->result();
And in my
View
#I echoed the vars as objects
$row->firstname

Invalid Argument Error Making Search Bar

I'm making a search bar for a site it works in one page but the other one I keep getting invalid argument error. Hopefully everything that is needed is below. I am using codeigniter. Please help. Thanks.
//Doesnt Work//
private function getUsers () {
$search = $this->input->post('search');
if($search && filter_var($search, FILTER_VALIDATE_EMAIL)) {
$where = 'WHERE source_adusers.ad_Email="'.$search.'"';
} else if ($search) {
$where = "WHERE source_adusers.ad_account='".$search."'";
} else if (!$search) {
$where = '';
}
$query = $this->db->query('SELECT *, COUNT(rollout_systems.EAM_USER) as systems FROM source_adusers
LEFT JOIN rollout_systems ON rollout_systems.EAM_User = source_adusers.ad_account '.$where.' GROUP BY source_adusers.ad_account LIMIT 0,50');
$users = null;
foreach ($query->result() as $row) {
$data['account'] = $row->ad_account;
$data['email'] = $row->ad_Email;
$data['name'] = $row->ad_DispName;
$data['systems'] = $row->systems;
$users[] = $data;
}
if(isset($this->data['users'])) {
$this->data['users'] = $users;
} else {
$this->data['users'] = $users;
}
}
//Does Work//
private function getSystems () {
$search = $this->input->post('search');
if ($search) {
$where = 'WHERE disc_systempool.ad_name="'.$search.'"';
} else {
$where = '';
}
$query = $this->db->query('SELECT *, COUNT(rollout_systems.sys_name) as scopes FROM disc_systempool LEFT JOIN rollout_systems
ON rollout_systems.sys_name=disc_systempool.ad_name '.$where.' GROUP BY disc_systempool.ad_name LIMIT 0,50');
foreach ($query->result() as $row) {
$data['model'] = $row->eam_Model;
$data['account'] = $row->ad_name;
$data['city'] = $row->eam_City;
$data['scopes'] = $row->scopes;
$data['search'] = $this->input->post('search');
$systems[] = $data;
}
if(isset($this->data['systems'])) {
$this->data['systems'] = $systems;
} else {
$this->data['systems'] = $systems;
}
}
//Where I'm getting the error//
<tbody>
<? foreach ($users as $user) { ?> <---- Line 18
<tr>
<td class="center"><?=$user['account']?></td>
<td><?=$user['name']?></td>
<td><?=$user['email']?></td>
<td class="center"><?=$user['systems']?></td>
<td class="center">View Details</td>
</tr>
<? } ?>
</tbody>
//Error//
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: headquarters/users.php
Line Number: 18
It shows the right thing. I fixed the problem. I misunderstood what the guy that hired me asked me to do. He said search account name. I was search display name which kept giving me the error.
Try making a var_dump($data); inside your view. If empty. Do the same in your controller by just printing it out. If you see data inside the $data array. Make sure that you are sending the $data array with you into the view $this->load->view("view",$data);
Besides that, i might be wondering why you do foreach on your rows inside of the controller instead of just using the object right in your view
return $query->result();
in view
foreach($users as $user) { print $user->account; }
Hope you figure it out.
Best regards
Jonas

Categories