Mapping Multidimensional Array Objects to Variables in a Class - php

I am using PDO to query a MySQL database and return an array of bikes based on their model type. The multi-dimensional array that is returned contains various attributes (part number, color, size, etc.) and is indexed by incrementing numeric keys. Something like this:
[0] => Array
(
[ItemId] => KL-5000-Y
[SeatType] => Leather
[Speed] => 5
[Model] => Killer
[Color] => Yellow
)
[1] => Array
(
[ItemId] => KL-5000-B
[SeatType] => Leather
[Speed] => 5
[Model] => Killer
[Color] => Black
)
This array is assigned to the variable $results
I then have a class named Bike that is intended to map the various attributes to protected variables that I can access elsewhere in my application with public getter methods. Some of these methods contain additional logic, but the primary goal here is to add a layer of abstraction between the database structure and the representation of the attributes elsewhere in the application.
class Bike
{
private $ItemId;
private $SeatType;
private $Model;
private $Color;
public function __construct($results)
{
if(is_array($results)) {
$this->ItemId = $result[x]['ItemId'];
$this->SeatType = $result[x]['SeatType'];
$this->Model = $result[x]['Model'];
$this->Color = $result[x]['Color'];
}
}
public function getItemId()
{
return $this->ItemId;
}
public function getSeatType()
{
return $this->SeatType;
}
//etc.
The issue I am running into is:
1.) Figuring out how to properly traverse the array in my Bike class (see "[x]" above)
2.) Then figuring out how to properly instantiate the objects in my html template
The goal is to have a table that lists all of the attributes for a particular model, indexed by Item Id:
<table>
<thead>
<th>ITEM ID</th>
<th>SEAT TYPE</th>
<th>MODEL</th>
<th>COLOR</th>
</thead>
<tbody>
<?php $bike = new Bike($results); ?>
<tr>
<td><?php echo $bike->getItemId();?></td>
<td><?php echo $bike->getSeatType();?></td>
<td><?php echo $bike->getModel(); ?></td>
<td><?php echo $bike->getColor(); ?></td>
</tr>
</table>
I can get the above to echo out one object, but not multiple. Apologize in advance. I am relatively new to programming and I assume this has a relatively simple solution but I have not been able to figure it out or find it elsewhere on SO.
Thanks for any help in advance!

You're thinking about it in the wrong way. You're trying to turn an array of attributes for multiple bikes into a bike, when you should be turning an array multiple bike attributes into an array of bikes.
To get this idea into code, use this for your class:
class Bike
{
private $ItemId;
private $SeatType;
private $Model;
private $Color;
public function __construct($result)
{
if(is_array($result)) {
// since $results is now only a single array, there is no need for [x]
$this->ItemId = $result['ItemId'];
$this->SeatType = $result['SeatType'];
$this->Model = $result['Model'];
$this->Color = $result['Color'];
}
}
public function getItemId()
{
return $this->ItemId;
}
public function getSeatType()
{
return $this->SeatType;
}
.....
So, first we need to put our bikes into an array:
<?php
$bikes = array();
foreach ($results as $key => $attributes) {
$bikes[] = new Bike($attributes);
}
?>
Then print out each bike into your table:
<table>
<thead>
<th>ITEM ID</th>
<th>SEAT TYPE</th>
<th>MODEL</th>
<th>COLOR</th>
</thead>
<tbody>
<?php foreach ($bikes as $key => $bike): ?>
<tr>
<td><?php echo $bike->getItemId();?></td>
<td><?php echo $bike->getSeatType();?></td>
<td><?php echo $bike->getModel(); ?></td>
<td><?php echo $bike->getColor(); ?></td>
</tr>
<?php endforeach ?>
</table>

PDO can return more types than just arrays. Actually, one way it can return data is as an instantiated object. Not even as just a stdObject either.
Check this out:
class Bike
{
public $id;
public $seatType;
public $model;
public $color;
public function getColor(){return $this->color}
}
$stmt = $pdo->prepare('SELECT * FROM bike');
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_CLASS, 'Bike');
This will return an array of instantiated bikes.

Related

Php language class usage issue

My php multilanguage class returns translated text by field when i call the class. I use echo for return translated text because i fetch whole page in class and translate them in foreach. Problem is when i return translated text with echo, $lang->Translate("PLANT") it jumps outside where i put it. How can i solve this issue. (By the way i can't use just return it only returns 1 row of language table)
The Language Table
echo '
<div class="table-responsive">
<table class="table table-striped table-hover">
<thead class="thead-light">
<tr>
<th scope="col"></th>
<th scope="col"><b></b></th>
<th scope="col"><b>'.$lang->Translate("PLANT").'</b></th>
<th scope="col" class="d-none d-sm-table-cell"><b>'.$lang->Translate("COMPANY").'</b></th>
<th scope="col" class="d-none d-sm-table-cell"><b></b></th>
<th scope="col" class="d-none d-sm-table-cell"><b></b></th>
<th scope="col" class="d-none d-sm-table-cell"><b></b></th>
<th scope="col" class="d-none d-sm-table-cell"><b></b></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
';
my language class
class Lang {
public function Language()
{
static $table = array();
static $loaded = false;
if (!$loaded) {
$loaded = true;
$lang = strtoupper(substr($_SERVER["HTTP_ACCEPT_LANGUAGE"], 0, 2));
include("settings.php"); //DB Connection
$sql = $MYSQLdb->prepare("SELECT * FROM language");
$sql->execute();
while($print = $sql->fetch(PDO::FETCH_ASSOC))
{
$field = array($print["FIELD"] => $print[$lang]);
array_push($table, $field);
}
return $table;
} else {
return $table;
}
}
public function Translate($translate)
{
$table = $this->Language();
foreach($table as $fields) {
echo $fields[$translate];
}
}
}
$lang = new Lang();
As when you do this
$field = array($print["FIELD"] => $print[$lang]);
you are making an array of word,translation i.e.
COMPANY ENTERPRISE
PLANT PLANTE
I see no reason why you cannot return the translation from this method I would change the method slightly as there seems to be no reason for a loop.
public function Translate($translate)
{
$table = $this->Language();
return $table[$translate];
}
Or even like this so you dont need to make a copy of the array
public function Translate($translate)
{
return $this->Language()[$translate];
}
I could go into further improvements to your class but I will focus on your particular issue.
In short change echo to return and the output will be included in your table markup:
public function Translate($translate)
{
$table = $this->Language();
foreach($table as $fields) {
return $fields[$translate];
}
}
Now that is only going to work if that function always returns 1 word because it is going to exit your foreach loop. If the foreach is not neccessary then do this instead (as now mentioned by #RiggsFolly):
public function Translate($translate)
{
$table = $this->Language();
return $table[$translate];
}

Can't Loop The Data in Codeigniter HTML Table

I want to create a loop for my database result. But I can't make it work on my VIEW file.
So here's my model:
<?php class Dash_model extends CI_Model {
public function __construct()
{
parent::__construct();
// Loading second db and running query.
$CI = &get_instance();
//setting the second parameter to TRUE (Boolean) the function will return the database object.
$this->db2 = $CI->load->database('db2', TRUE);
}
public function query0()
{
$query = $this->db2->query("SELECT name FROM table1 ORDER BY date");
return ($query->result());
}
public function query1()
{
$query = $this->db->query("MY QUERY HERE, RUNS OK");
$result = $query->result_array();
return $result;
}
public function query2()
{
$query = $this->db->query("MY QUERY HERE, RUNS OK");
$result = $query->result_array();
return $result;
}
public function query3()
{
$query = $this->db->query("MY QUERY HERE, RUNS OK");
$result = $query->result_array();
return $result;
}
public function query4()
{
$query = $this->db->query("MY QUERY HERE, RUNS OK");
$result = $query->result_array();
return $result;
}
}
Let's say that my query works ok, I've tested it on my SQL Server. And then here's my CONTROLLER:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Dash_control extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('dash_model');
$this->load->library('table');
}
public function index()
{
$tmpl = array (
'row_start' => '<tr>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
);
$this->table->set_template($tmpl);
$data['result0'] = $this->dash_model->query0();
$data['result1'] = $this->dash_model->query1();
$data['result2'] = $this->dash_model->query2();
$data['result3'] = $this->dash_model->query3();
$data['result4'] = $this->dash_model->query4();
$this->load->view('dashboard',$data);
}
}
So i have 5 function in my model, the result was supposed to be a LOOP data. After I put the model inside my CONTROLLER, I pass it to my VIEW file like this:
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Name</th>
<th>Transaction Success</th>
<th>Transaction Failure</th>
<th>Total Visit</th>
<th>Total Item</th>
</tr>
</thead>
<tbody>
<?php foreach (array_combine($result0, $result1, $result2, $result3, $result4) as $row)
{ ?>
<tr>
<td><?php echo $row->queryalias0; ?></td>
<td><?php echo $row->queryalias1; ?></td>
<td><?php echo $row->queryalias2; ?></td>
<td><?php echo $row->queryalias3; ?></td>
<td><?php echo $row->queryalias4; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
The error I got was:
Message: array_combine(): Both parameters should have an equal number of elements
And:
Message: Invalid argument supplied for foreach()
The result that I would like to achieve should be like this:
Thank you guys, for all your help...
From php.net
array_combine — Creates an array by using one array for keys and
another for its values
array array_combine ( array $keys , array $values )
You using wrong way array_combine function. You can try array_merge instead
foreach (array_merge($result0, $result1, $result2, $result3, $result4) as $row)

Select Data Not Work on CodeIgniter?

I have MVC on CI that not show error but cant get the result.
This the Script
Controller
customer.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Customer extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function index()
{
$this->load->view('customer_view');
}
function tampil_customer()
{
$this->load->model('customer_model');
$data = array('tests' => $this->customer_model->tampil_data_customer());
$this->load->view('customer_view', $data);
}//end fucnntion
}//end class
?>
Model
customer_model.php
<?php
class Customer_model extends CI_Models
{
public function tampil_data_customer()
{
$results = array();
$this->db->select('*');
$this->db->from('customer');
$query = $this->db->get();
if($query->num_rows() > 0)
{
$results = $query->result();
}
return $results;
}
}
?>
View
customer_view.php
<table border="1" align="center" widht="900">
<tr>
<td colspan="5" align="center"><h2>Data Customer</h2></td>
</tr>
<tr>
<th>Nama</th>
<th>Company</th>
<th>Alamat</th>
<th>Telepon</th>
<th>HP</th>
</tr>
<?php
//$result = $this->result();
if( !empty($results) )
{
foreach($results as $isi)
{
echo "<tr>";
echo "<td>$isi->nama</td>";
echo "<td>$isi->company</td>";
echo "<td>$isi->alamat</td>";
echo "<td>$isi->telepon</td>";
echo "<td>$isi->hp</td>";
//echo anchor('customer/edit_customer/'.$isi->ID, 'Edit')."|";
//echo anchor('customer/hapus_customer/'.$isi->ID, 'Hapus')."|";
echo "</tr>";
}
}
?>
</table>
the Result only show the HTML like this
Can Anyone Help me to Fix this Problem?
Im very new Using CodeIgniter. I never use Framework before.
Im very appreciated your Answer.
Thanks
You are storing the result from database to array tests here
$data['tests'] = $this->customer_model->tampil_data_customer();
and trying to call it in view with an undefined array $results.
Try with this.
if(!empty($tests->result())){
foreach($tests->result() as $isi)
{
echo "<tr>";
echo "<td>".$isi->nama."</td>";
echo "<td>".$isi->company."</td>";
echo "<td>".$isi->alamat."</td>";
echo "<td>".$isi->telepon."</td>";
echo "<td>".$isi->hp."</td>";
echo "</tr>";
}
}
In model can you make it simple like this,
public function tampil_data_customer()
{
$query=$this->db->query('select * from customer');
$results = $query->result();
return $results;
}
when you pass in arguments using $this->load->view() function,you are using the view() function with the instance of Loader load,it's in /system/core/Loader.php. As the block comments say
An associative array of data to be extracted for use in the view.
if you pass in an object,you can get the public properties by simply using the property name,you can't get the protected and private property.
if you pass in an Multi-dimensional Array,you can get the value by using key/keys in the Multi-dimensional Array.
By the way,you must pass in an array or object other a variable.
sample below
model.php(application\models\test)
class model extends CI_Model {
public $ss=1;
protected $bb=1;
private $vv=3;
}
controller.php(application\controllers)
class Hello extends CI_Controller
public function __construct() {
parent::__construct ();
}
public function index() {
$this->load->model('test/model');
$model=new model();
$this->load->view ( 'test/view', $model );
}
view.php(application\views\test)
echo $ss;
then you get the value of object.

Table data not showing in codeigniter?

CONTROLLER FUNCTION
public function displayallquestionsandoptions() {
$this->load->database();
$this->load->library('table');
$query = $this->db->query("SELECT QuestionId,Name,SurveyId,CreatedOn from question");
$table = $this->table->generate($query);
return $table; //Added this
}
Calling in another function:
$questionstable = $this->displayallquestionsandoptions();
$this->load->view('questions', $questionstable);
VIEW CODE:
<table>
<thead>
<th>Question Id</th>
<th>Question Name</th>
<th>Survey Id</th>
<th>Created On</th>
</thead>
<tbody>
<?php foreach ($questionstable as $questionrow) ?>
<tr>
<td><?php $questionrow -> QuestionId;?></td>
<td><?php $questionrow ->Name;?></td>
<td><?php $questionrow ->SurveyId;?></td>
<td><?php $questionrow ->CreatedOn;?></td>
</tr>
<?phpendforeach;?>
</tbody>
</table>
I am unable to access the array variable please help someone do i need a model can i work without it?
It should be
return $table; //good
and not
return; $table; //bad
You don't need the ; after return unless you want to return nothing.
In your calling function, do this too:
$questionstable['dataquestions'] = $this->displayallquestionsandoptions();
$this->load->view('questions', $questionstable);
You're referring to $dataquestions in your view, but that variable doesn't exist.
Also, in your foreach, you're missing the : at the end.
It should be:
foreach($dataquestions as $questionsrow):
try this
first load this
$this->load->library('table');
public function displayallquestionsandoptions() {
$this->load->database();
$this->load->library('table');
$query = $this->db->query("SELECT QuestionId,Name,SurveyId,CreatedOn from question");
return $query->result_array();
}
$questionstable = $this->displayallquestionsandoptions();
$this->load->view('questions', $questionstable);
in view just use this
echo $this->table->generate($questionstable);
no foreach needed for more info check this
http://ellislab.com/codeigniter/user-guide/libraries/table.html
Try with this :
In Controller return the query object
public function displayallquestionsandoptions() {
$this->load->database();
$this->load->library('table');
$query = $this->db->query("SELECT QuestionId,Name,SurveyId,CreatedOn from question");
return $query; //Added this
}
In other function, try like
$data['questionstable'] = $this->displayallquestionsandoptions();
$this->load->view('questions', $data);
and in view fetch details like
<?php foreach ($questionstable->result() as $questionrow) ?>
<tr>
<td><?php echo $questionrow -> QuestionId;?></td>
<td><?php echo $questionrow ->Name;?></td>
<td><?php echo $questionrow ->SurveyId;?></td>
<td><?php echo $questionrow ->CreatedOn;?></td>
</tr>
<?php endforeach;?>
I think you forgot to write little code:Change below line with your line in public function displayallquestionsandoptions() {} method
$table = $query->result_array();
and little change In your calling another function line...
$data['questionstable'] = $this->displayallquestionsandoptions();
$this->load->view('questions', $data);

mysql_fetch_object with specific class

I developed an object-oriented guestbook and I have my Class GuestBookEntry:
class GuestBookEntry {
protected $id;
protected $entryDate;
protected $authorName;
protected $authorMail;
protected $entryText;
// getters, setters and specific functions are omitted
}
I also have a mysql table with the same names as columns.
Well, when I fetch guestbook entries, it seems to work, but it only displays the ID and the Date, which where returned by getters. The other things won't return to the template.
The code looks like this:
public function showEntries() {
$query = mysql_query('SELECT * FROM dng_entries ORDER BY id DESC');
while($entry = #mysql_fetch_object($query, 'GuestBookEntry')) {
if(empty($entry)) {
echo '<font color="white">Keine Einträge vorhanden...</font>';
} else {
var_dump($entry);
echo '<table class="table table-bordered entryfield" align="right">
<thead>
<tr>
<td rowspan="2">'.$entry->getId().'</td>
<td width="20%">Datum:</td>
<td>Name:</td>
<td>Email:</td>
</tr>
<tr>
<td>'.$entry->getEntryDate().'</td>
<td>'.$entry->getAuthorName().'</td>
<td>'.$entry->getAuthorMail().'</td>
</thead>
<tbody>
<tr>
<td width="10%" valign="middle">Eintrag:</td>
<th colspan="3" valign="top" height="100px">'.$entry->getEntryText().'</td>
</tr>
</tbody>
</table>';
}
}
}
Here's a var_dump of e.g. object:
object(GuestBookEntry)#2 (5) { ["id":protected]=> string(1) "2" ["entryDate":protected]=> int(1344696811) ["authorName":protected]=> NULL ["authorMail":protected]=> NULL ["entryText":protected]=> NULL }
update: well here is the rest of GuestBookEntry class:
public function __construct($authorName, $authorMail, $entryText) {
$this->authorName = $authorName;
$this->authorMail = $authorMail;
$this->entryDate = time();
$this->entryText = $entryText;
}
public function getId() {
return $this->id;
}
public function getAuthorName() {
return (String) $this->authorName;
}
public function getAuthorMail() {
return (String) $this->authorMail;
}
public function getEntryDate() {
return date('d.n.Y', $this->entryDate);
}
public function getEntryText() {
return $this->entryText;
}
public function setAuthorName($authorName) {
$this->authorName=$authorName;
}
public function setAuthorMail($authorMail) {
$this->authorMail=$authorMail;
}
public function setEntryDate($entryDate) {
$this->entryDate=$entryDate;
}
public function setEntryText($entryText) {
$this->entryText=$entryText;
}
Your problem is case sensitivity. MySQL column names don't deal with camel case, but PHP see's a difference between properties based on case such as $entryDate and $entrydate. Stick to lowercase with underscores if you need visual seperation. The reason why id works is it's all lower case.
I think if you simply lowercase all your property names that are supposed map to table columns everything will work.
BTW... The camel case issue with column names may vary based on the OS running the sql server.

Categories