The code shown below is used to manually fill an array.
<?php
include_once 'include/DatabaseConnector.php';
$data = array(
array(0,array("111",' EE112',' AA','FT445'),"2004-03-01 10:00","2004-03-01 14:00"),
array(1,array("111",' BC124',' RYA','FE675'),"2004-03-01 16:00","2004-03-01 18:00"),
array(2,array("11",' BE225',' FA','AE667'),"2004-03-01 09:00","2004-03-01 10:00"),
array(3,array("11",' TC828',' BA','FF745'),"2004-03-01 06:00","2004-03-01 08:00")
);
?>
Now I want to fill this array from the database:
$query1="SELECT * FROM MyData;";
$result1=DatabaseConnector::ExecuteQueryArray($query1);
<?php foreach ($result1 as $row):?>
<tr>
<td><?php echo $row['resReg']; ?></td>
<td><?php echo $row['resTitle']; ?></td>
<td><?php echo $row['resAvailability'] ? 'Yes' : 'No';?></td>
</tr>
<?php endforeach;?>
How to assign the columns of result1 to the columns of the array?
Am i right assuming you want to do something like this:
<?php
$query1 = "SELECT name,color1,color2 FROM MyPets;";
$result1 = DatabaseConnector::ExecuteQueryArray($query1);
$petArray = array();
foreach($result1 as $pet):
$petArray[] = array('name' => $pet['name'],
'colors' => array(
$pet['color1'],
$pet['color2'])
);
?>
Related
I want to display the results of the $ distance variable to the table in the view file.
But I get an error in my script, can anyone help solve this error?
I also want to sort the results of the $ distance variable from the smallest.
Error appears in line 38, which is in the foreach function in my view file.
This is the script from my controller file :
function index()
{
$center_lat = -7.2574719;
$center_lng = 112.7520883;
$data= $this->m_metode->tampil_data_fotografer();
{
foreach($data->result_array() as $row)
{
$lat=(float)$row['latitude'];
$lng=(float)$row['longitude'];
// $distance= $lat * $center_lat;
$distance['tb_fotografer'] =( 6371 * acos((cos(deg2rad($center_lat)) ) * (cos(deg2rad($lat))) *
(cos(deg2rad($lng) - deg2rad($center_lng)) )+ ((sin(deg2rad($center_lat))) *
(sin(deg2rad($lat))))));
// var_dump($distance);
}
}
$this->load->view('public/pencari/v_tampil_rekomendasi',$distance);
}
My view :
<?php
$no = 1;
foreach($tb_fotografer->result_array() as $fg){
?>
<tr>
<td><?php echo $no++ ?></td>
<td><?php echo $fg->nama ?></td>
<td><?php echo $fg->alamat ?></td>
<td><?php echo $fg->kamera ?></td>
<td><?php echo $fg->spesifikasi_foto ?></td>
<td><?php echo $fg->keahlian_foto ?></td>
<td><?php echo $fg->latitude ?></td>
<td><?php echo $fg->longitude ?></td>
</tr>
<?php } ?>
This variable "$tb_fotografer" store a float value not an array, and you can not access with result_array(). you must store as an array like this:
$distance['tb_fotografer'][] = ( 6371 * acos((cos(deg2rad($center_lat)) ) * (cos(deg2rad($lat))) *
(cos(deg2rad($lng) - deg2rad($center_lng)) )+ ((sin(deg2rad($center_lat))) *
(sin(deg2rad($lat))))));
base on your view field you needed to send $data to your view file.
$this->load->view('public/pencari/v_tampil_rekomendasi',['tb_fotografer' => $data->result_array()]);
and in your view file:
foreach($tb_fotografer as $fg){
for sort you can store data in another variable like $output and put distance on it, after that you can sort with this method: usort($array, "cmp");
after all the steps you can send to your view.
final code:
function index()
{
$center_lat = -7.2574719;
$center_lng = 112.7520883;
$data= $this->m_metode->tampil_data_fotografer();
$out = []
{
foreach($data->result_array() as $row)
{
$lat=(float)$row['latitude'];
$lng=(float)$row['longitude'];
// $distance= $lat * $center_lat;
$distance =( 6371 * acos((cos(deg2rad($center_lat)) ) * (cos(deg2rad($lat))) *
(cos(deg2rad($lng) - deg2rad($center_lng)) )+ ((sin(deg2rad($center_lat))) *
(sin(deg2rad($lat))))));
$out[] = array_merge($row, ['distance' => $distance]);
}
}
// #todo use usort for sort base on distance
$this->load->view('public/pencari/v_tampil_rekomendasi',['tb_fotografer' => $out]);
}
You've overwritten the $distance['tb_fotografer'] variable on each iteration and also you've accessed object on array data.
Try to modify the controller like this :
function index()
{
$center_lat = -7.2574719;
$center_lng = 112.7520883;
$data= $this->m_metode->tampil_data_fotografer();
{
foreach($data->result_array() as $key => $row)
{
$lat=(float)$row['latitude'];
$lng=(float)$row['longitude'];
// $distance= $lat * $center_lat;
$distance['tb_fotografer'][$key][] = $row; // get all of the preserved result_array data
$distance['tb_fotografer'][$key][]['distance'] = ( 6371 * acos((cos(deg2rad($center_lat)) ) * (cos(deg2rad($lat))) *
(cos(deg2rad($lng) - deg2rad($center_lng)) )+ ((sin(deg2rad($center_lat))) *
(sin(deg2rad($lat))))));
// var_dump($distance);
}
}
$this->load->view('public/pencari/v_tampil_rekomendasi',$distance);
}
And the v_tampil_rekomendasi view like this :
<?php
$no = 1;
foreach($tb_fotografer as $fg){
?>
<tr>
<td><?php echo $no++ ?></td>
<td><?php echo $fg['nama'] ?></td>
<td><?php echo $fg['alamat'] ?></td>
<td><?php echo $fg['kamera'] ?></td>
<td><?php echo $fg['spesifikasi_foto'] ?></td>
<td><?php echo $fg['keahlian_foto'] ?></td>
<td><?php echo $fg['latitude'] ?></td>
<td><?php echo $fg['longitude'] ?></td>
<td><?php echo $fg['distance'] ?></td>
</tr>
<?php } ?>
I have a table that store the data of ID, ID Login, Name, etc. But i just want to show the data based on ID Login
Here My Controller :
function index(){
$data['hasil'] = $this->M_user_lapor->index_model();
$this->load->view('v_user_lapor/index', $data);
}
My Model :
function index_model(){
$baca = $this->db->query('select * from user_lapor');
if($baca->num_rows() > 0){
foreach ($baca->result() as $data){
$hasil[] = array(
'id_login'=>$data->id_login,
'id_lapor'=>$data->id_lapor,
'nm_unit'=>$data->nm_unit,
'pic_1'=>$data->pic_1,
'pic_2'=>$data->pic_2,
'ip_wan'=>$data->ip_wan,
'ip_lan'=>$data->ip_lan,
'prov'=>$data->prov,
'icn_sid'=>$data->icn_sid,
'tlkm_sid'=>$data->tlkm_sid,
'status'=>$data->status,
);
}
return json_encode ($hasil);
}else{
return false;
}
}
View :
<tbody>
<?php
if ($hasil){
$no = 1;
$array = json_decode($hasil, true);
foreach($array as $data) {
?>
<tr>
<td class="text-center"><?php echo $no++;?></td>
<td><?php echo $data['nm_unit'];?></td>
<td><?php echo $data['pic_1'];?></td>
<td><?php echo $data['pic_2'];?></td>
<td><?php echo $data['ip_wan'];?></td>
<td><?php echo $data['ip_lan'];?></td>
<td><?php echo $data['prov'];?></td>
<td><?php echo $data['icn_sid'];?></td>
<td><?php echo $data['tlkm_sid'];?></td>
</tr>
<?php
}
}
?>
</tbody>
As you can see, there is id_login inside my model, and i want to show the table data based on it, hopefully somebody can help me because i'm just using the codeigniter, thnaks
I solved this by myself, lol. I just pass the id_login value from session, so i add this to my controller :
function index(){
$id_login = $this->session->id_login;
$data['hasil'] = $this->M_user_lapor->index_model($id_login);
$this->load->view('v_user_lapor/index', $data);
}
And call it to my model :
function index_model($id_login){
$baca = $this->db->query('select * from user_lapor where id_login='.$id_login);
if($baca->num_rows() > 0){
foreach ($baca->result() as $data){
$hasil[] = array(
'id_login'=>$data->id_login,
'id_lapor'=>$data->id_lapor,
'nm_unit'=>$data->nm_unit,
'pic_1'=>$data->pic_1,
'pic_2'=>$data->pic_2,
'ip_wan'=>$data->ip_wan,
'ip_lan'=>$data->ip_lan,
'prov'=>$data->prov,
'icn_sid'=>$data->icn_sid,
'tlkm_sid'=>$data->tlkm_sid,
'status'=>$data->status,
);
}
return json_encode ($hasil);
}else{
return false;
}
}
Here is my model - I want to assign the rows and echo out on the view page e.g
My Model:
public function dsduan(){
$data = array();
$q = $this->db->query("SELECT duan.id, duan.tenduan, duan.diachi, quan.quan, duan.tdt, duan.mdxd, duan.tt, duan.cdt, duan.dvql, duan.dvtk, duan.dvtc, duan.dvgs, duan.loai, duan.tienich, duan.noidung, duan.hinhanh FROM duan LEFT JOIN quan ON duan.quan=quan.id ORDER BY duan.tenduan ASC");
if ($q->num_rows == 1)
{
foreach ($q->result() as $row)
{
$data[]['id'] = $row->id;
$data[]['tenduan'] = $row->tenduan;
$data[]['diachi'] = $row->diachi;
$data[]['quan'] = $row->quan;
}
}
return $data;
}
My Controller:
public function dsduan() {
$this->load->model('madmin');
$duan = $this->madmin->dsduan();
$this->load->view('danhsachduan', $duan);
}
My View:
<td><?php echo $id; ?></td>
<td><?php echo $tenduan; ?></td>
<td><?php echo $diachi; ?></td>
<td><?php echo $quan; ?></td>
How do I properly pass my model array to my controller so that I can echo out on my view?
My view Error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: id
Filename: views/danhsachduan.php
Line Number: 44
In your model you use two dimensional array:
$data[]['id'] = $row->id;
then in your controller you pass this array to view.
so if you want to access two dimensional array into your view, you have to use foreach loop.
such as change your array in model like following:
$data['id'][] = $row->id;
and in your view access array using:
foreach($id as $res)
{
echo $res;
}
update your view like this
<?php foreach($duan as $d) { ?>
<td><?php echo $d['id']; ?></td>
<td><?php echo $d['tenduan']; ?></td>
<td><?php echo $d['diachi']; ?></td>
<td><?php echo $d['quan']; ?></td>
<?php } ?>
public function dsduan(){
$data = array();
$q = $this->db->query("SELECT duan.id, duan.tenduan, duan.diachi, quan.quan, duan.tdt, duan.mdxd, duan.tt, duan.cdt, duan.dvql, duan.dvtk, duan.dvtc, duan.dvgs, duan.loai, duan.tienich, duan.noidung, duan.hinhanh FROM duan LEFT JOIN quan ON duan.quan=quan.id ORDER BY duan.tenduan ASC");
if ($q->num_rows == 1)
{
foreach ($q->result() as $row)
{
$data['id'] = $row->id;
$data['tenduan'] = $row->tenduan;
$data['diachi'] = $row->diachi;
$data['quan'] = $row->quan;
}
}
return $data;
}
In codeigniter, it use extract() method when binding variable from controller to view. In this case, you can do like this.
In Model
public function dsduan()
{
$data = array();
$q = $this->db->query("SELECT duan.id, duan.tenduan, duan.diachi, quan.quan, duan.tdt, duan.mdxd, duan.tt, duan.cdt, duan.dvql, duan.dvtk, duan.dvtc, duan.dvgs, duan.loai, duan.tienich, duan.noidung, duan.hinhanh FROM duan LEFT JOIN quan ON duan.quan=quan.id ORDER BY duan.tenduan ASC");
if ($q->num_rows)
{
$data = $q->result_array();
}
return $data;
}
In Controller
public function dsduan()
{
$this->load->model('madmin');
$data['duan'] = $this->madmin->dsduan();
$this->load->view('danhsachduan', $data);
}
In View, if your array is multi-dimensional, you can use like this,
<?php foreach($duan as $d) { ?>
<td><?php echo $d['id']; ?></td>
<td><?php echo $d['tenduan']; ?></td>
<td><?php echo $d['diachi']; ?></td>
<td><?php echo $d['quan']; ?></td>
<?php } ?>
if your array is one-dimensional, you can use like this,
<td><?php echo $duan['id']; ?></td>
<td><?php echo $duan['tenduan']; ?></td>
<td><?php echo $duan['diachi']; ?></td>
<td><?php echo $duan['quan']; ?></td>
Have modified your code. Kindly replace below with your code.
Model:
public function dsduan()
{
$q = $this->db->query("SELECT duan.id, duan.tenduan, duan.diachi, quan.quan, duan.tdt, duan.mdxd, duan.tt, duan.cdt, duan.dvql, duan.dvtk, duan.dvtc, duan.dvgs, duan.loai, duan.tienich, duan.noidung, duan.hinhanh FROM duan LEFT JOIN quan ON duan.quan=quan.id ORDER BY duan.tenduan ASC");
if($q->num_rows() > 0)
return $q->result();
return false;
}
Controller:
public function dsduan()
{
$this->load->model('madmin');
$data['duan'] = $this->madmin->dsduan();
$this->load->view('danhsachduan', $data);
}
View:
<?php foreach($duan as $d) { ?>
<td><?php echo $d->id; ?></td>
<td><?php echo $d->tenduan; ?></td>
<td><?php echo $d->diachi; ?></td>
<td><?php echo $d->quan; ?></td>
<?php } ?>
I am writing a shopping cart and have my data stored in the $_SESSION array, but would like to calculate a total. below it the code I thought would work to do this, but it returns '1' in stead of a total!
$total = array($_SESSION['qty'],$_SESSION['pr']);
/* I'll give you more code...thanks for your help!!
here is the code for my php cart:
<?php
function item_list()
{
if(isset($_SESSION['qty'])){
$total = array($_SESSION['qty'],$_SESSION['pr']);
foreach($_SESSION['qty'] as $key => $value)
{?>
<tr>
<td align="center"><?php echo $_SESSION['item'][$key]; ?></td>
<td align="center"><?php echo $value; ?></td>
<td align="center"><?php echo $_SESSION['pr'][$key]; ?></td>
<td align="center"><?php echo array_product($total); ?>
</tr><?php
}
}
}
session_start();
if(isset($_POST['clear']) && ($_POST['clear'] == 'clear'))
{
session_destroy();
unset($_SESSION['qty']);
unset($_SESSION['item']);
unset($_SESSION['pr']);
unset($_POST['qty']);
unset($_POST['item']);
unset($_POST['pr']);
}
if(!isset($_SESSION['qty'])) $_SESSION['qty'] = array();
if(!isset($_SESSION['item'])) $_SESSION['item'] = array();
if(!isset($_SESSION['pr'])) $_SESSION['pr'] = array();
if(isset($_POST['qty']))
{
foreach($_POST['qty'] as $value)
{
if(!$value == '') array_push($_SESSION['qty'], filter_var($value,
FILTER_SANITIZE_SPECIAL_CHARS));
}
foreach($_POST['item'] as $key => $value)
{
if(!$_POST['qty'][$key] == '') array_push($_SESSION['item'], filter_var($value,
FILTER_SANITIZE_SPECIAL_CHARS));
}
foreach($_POST['pr'] as $key => $value)
{
if(!$_POST['qty'][$key] == '') array_push($_SESSION['pr'], filter_var($value,
FILTER_SANITIZE_SPECIAL_CHARS));
}
}
?>
That is a strange way to structure a shopping cart, but here's how to do it with that structure:
foreach($_SESSION['qty'] as $key => $value)
{
$total = $_SESSION['qty'][$key] * $_SESSION['pr'][$key];
?>
<tr>
<td align="center"><?php echo $_SESSION['item'][$key]; ?></td>
<td align="center"><?php echo $value; ?></td>
<td align="center"><?php echo $_SESSION['pr'][$key]; ?></td>
<td align="center"><?php echo $total; ?>
</tr><?php
}
If you wanted to get a total of all quantity and cost of the cart:
function getTotals()
{
$total = array('qty' => 0, 'price' => 0);
foreach($_SESSION['qty'] as $key => $qty)
{
$total['qty'] += $qty;
$total['price'] += ($_SESSION['pr'][$key] * $qty)
}
return $total;
}
$total = getTotals();
echo $total['qty']; // output the total quantity of items
echo $total['price']; // output the total cost for all items and quantity
I would recommend a better structure though, something like:
$_SESSION['cart']['items'] = array(
array(
'name' => 'Screwdriver',
'price' => 5,
'qty' => 2,
),
array(
'name' => 'Hammer',
'price' => 10,
'qty' => 1,
)
);
As per your cart array it is not able to hold multiple products you have to use multy dimensional array like this
$_SESSION['cart_items'] = array(
array( "qty"=>5, "item"=>"tshirt", "pr"=>50.20),
array( "qty"=>2, "item"=>"Cell Phone", "pr"=>50.20),
array( "qty"=>7, "item"=>"", "pr"=>50.20),
)
then you can write your code like this
function item_list()
{
foreach($_SESSION['cart_items'] as $item_array)
{?>
<tr>
<td align="center">Item:<?php echo $item_array['item']; ?></td>
<td align="center">Qty: <?php echo $item_array['qty']; ?></td>
<td align="center">Price :<?php echo $item_array['pr']; ?></td>
<td align="center">Total : <?php echo $item_array['qty'] * $item_array['pr']; ?>
</tr><?php
}
}
You should create yourself a Card class that is able to import/export data from the $_SESSION superglobal (or some other array if you mock it for tests, testing with $_SESSION can be akward) which is able to handle your data-structure easily and can calculate the total, too:
$cart = new Cart();
$cart->importFromArray($_SESSION);
// or:
$cart->importFromArray($_SESSION['cart']);
// later on:
$total = $cart->getTotal();
// somewhere else:
$cart->addItem(...);
...
$_SESSION['cart'] = $cart->exportToArray();
That will allow you to more easily change the code over time.
Hello
i'm started to learning cakephp framework.And just for start i wanted to write some simple game.
I have user controller wited already (not finished but works :D) and now i started to write equipment. But i stuck at the moment i'm trying to sort foreach by type (helmet, armor, shield etc) and now script output table like this:
Id Owner Name Status Type Cost
1 23 Krasnoludzka Salada B H 100
2 23 Jakieś spodnie B L 10
3 23 Zbroja B A 123
But i wanna to make it like this:
Id Owner Name Status Type Cost
Helmets:
1 23 Krasnoludzka Salada B H 100
4 23 Smocza Salada B H 100
Legs:
2 23 Jakieś spodnie B L 10
Armors:
3 23 Zbroja B A 123
Mine equipments_controller.php:
<?php
class EquipmentsController extends AppController {
var $name = 'Equipments';
var $helpers = array('Html', 'Form');
function index() {
$this->set('equipments', $this->Equipment->find('all', array('conditions' => array('owner='.$this->Session->read('Auth.User.id'), 'status=\'B\''))));
//$this->set('equipments', $this->Equipment->find('owner='.$this->Session->read('Auth.User.id')));
}
function view ($id = null) {
$this->Equipment->id = $id;
$owner = $this->Equipment->read('owner');
if ($owner['Equipment']['owner']==$this->Session->read('Auth.User.id')) {
$this->redirect(array('controller' => 'equipments', 'action' => 'index'));
$this->Session->setFlash('To nie twój przedmiot!');
} else {
$this->set('equipment', $this->Equipment->read());
}
}
}
And equipments/index.ctp:
<!-- File: /app/views/news/index.ctp (edit links added) -->
<h1>Plecak</h1>
<table>
<tr>
<th>Id</th>
<th>Owner</th>
<th>Name</th>
<th>Status</th>
<th>Type</th>
<th>Cost</th>
</tr>
<!-- Here's where we loop through our $news array, printing out news info -->
<?php foreach ($equipments as $equipment): ?>
<tr>
<td><?php echo $equipment['Equipment']['id']; ?></td>
<td><?php echo $equipment['Equipment']['owner']; ?></td>
<td><?php echo $equipment['Equipment']['name']; ?></td>
<td><?php echo $equipment['Equipment']['status'];?></td>
<td><?php echo $equipment['Equipment']['type']; ?></td>
<td><?php echo $equipment['Equipment']['cost']; ?></td>
</tr>
<?php endforeach; ?>
</table>
Can anyone help me?
You can add a 'group' option to your find()...
$this->set(
'equipments',
$this->Equipment->find(
'all',
array(
'conditions' => array(
'Equipment.owner' => $this->Session->read('Auth.User.id'),
'Equipment.status' => 'B'
),
'group' => array(
'Equipment.type'
),
'order' => array(
'Equipment.type',
'Equipment.name',
),
)
)
);
Hopefully you've actually got a Model for those types, and can use that model instead of those Equipment.type values, something like EquipmentType.name would be useful in your view. If you had that, then you'd be able to output a new heading row each time the EquipmentType.id changed.
I I'm understanding you correctly, you'd like to be able to sort your table of data by the titles in the table head tags.
If this is the case, I'd suggest using cake's built in paginator.
Your controller should look like:
class EquipmentsController extends AppController {
var $name = 'Equipments';
var $helpers = array('Html', 'Form');
public $paginate = array(
'Equipment' => array(
'limit' => 25,
'order' => array(
'Equipment.id' => 'ASC'
)
)
);
function index() {
$owner = $this->Session->read('Auth.User.id');
$equipments = $this->paginate('Equipment', array(
'Equipment.owner' => $owner,
'Equipment.status' => 'B'
));
$this->set(compact('equipments'));
}
}
Then in your views/equipments/index.ctp:
<!-- File: /app/views/news/index.ctp (edit links added) -->
<h1>Plecak</h1>
<table>
<tr>
<th><?=$this->Paginator->sort('Id', 'Equipment.id')?></th>
<th><?=$this->Paginator->sort('Owner', 'Equipment.owner')?></th>
<th><?=$this->Paginator->sort('Name', 'Equipment.name')?></th>
<th><?=$this->Paginator->sort('Status', 'Equipment.status')?></th>
<th><?=$this->Paginator->sort('Type', 'Equipment.type')?></th>
<th><?=$this->Paginator->sort('Cost', 'Equipment.cost')?></th>
</tr>
<!-- Here's where we loop through our $news array, printing out news info -->
<?php foreach ($equipments as $equipment): ?>
<tr>
<td><?php echo $equipment['Equipment']['id']; ?></td>
<td><?php echo $equipment['Equipment']['owner']; ?></td>
<td><?php echo $equipment['Equipment']['name']; ?></td>
<td><?php echo $equipment['Equipment']['status'];?></td>
<td><?php echo $equipment['Equipment']['type']; ?></td>
<td><?php echo $equipment['Equipment']['cost']; ?></td>
</tr>
<?php endforeach; ?>
Using the paginator this way will generate links in your table headers that will automatically sort the data coming out of the db.