Navigate through tables with zend framework - php

I'm getting started with Zend Framework. I have been doing some tutorials here and there.
In one of my views, i have this block of code:
<?php foreach($this->Instruments as $Instrument) : ?>
<tr>
<td><?php echo $this->escape($Instrument->nom);?></td>
<td><?php echo $this->escape($Instrument->idtypeofinstrument);?></td>
<td>
</td>
</tr>
<?php endforeach; ?>
idtypeofinstrument is a foreign key, right now it just displays the id. I'd like to display something else more explicit for the user.
My tables:
+------------------+
| typeofinstrument |
+------------------+
| id | -- primary key
| typeofinstrument | -- what I want to display
+------------------+
+--------------------+
| instrument |
+--------------------+
| id | -- primary key
| name |
| idtypeofinstrument | -- foreign key
+--------------------+

The simple way to do this, not really correct but simple.
//escape() removed for clarity
<?php foreach($this->Instruments as $Instrument) : ?>
<tr>
<td><?php echo $Instrument->nom;?></td>
<?php $table = new Application_Model_DbTable_Typeofinstument();
$select = $table->select()->where('id = ?',$Instrument->idtypeofinstrument);
$type = $table->fetchRow($select); ?>
<td><?php echo $type->typeofinstrument;?></td>
<td>
</td>
</tr>
<?php endforeach; ?>
To do it in a more correct manner would require the use of a mapper, ORM or some other solution to map the data in the table to an instrument object.
With the goal being for your original code to return the data you want.
To understand further check out:
http://phpmaster.com/building-a-domain-model/
http://phpmaster.com/integrating-the-data-mappers/
These articles helped me a lot with understanding mappers.

Related

PHP for html table with dynamic rows and columns where row data relies on column heading

I have created an assessment system that grades each pupil on each lesson. I have a form that creates a table with the following headings:
Pupil name
Pupil ID
Lesson title
Lesson ID
Lesson grade
To view the data I am trying to create a table that works a bit like a spreadsheet.
Where each row takes the pupil ID and searches in the database for the grade i.e.
SELECT * FROM table WHERE pupilid = "rowid" AND lessonid = "columnheading"
I can create the column and row headings using PHP with while loops, but I can't figure out how to make each cell link between the column heading and pupil ID.
The only way I have managed to create this is with floating divs.
It works but it is very hard to style and the names and grades are in different grids so it is difficult to sort.
I would really appreciate any help / links to ways to do this.
Each week new pupils could be added and each lesson column will be added to the spreadsheet.
The table should sort of look like the one below:
+-------+----+----+--- +
| Pupil | L1 | L2 | L3 |
+-------+----+----+----+
| John | B | C+ | D |
+-------+----+----+----+
| Sarah | B | A | F |
+-------+----+----+----+
| Jim | D | A | B |
+-------+----+----+----+
I can create the column/row headings using the code below. I would really appreciate some help getting the code for the grade bit.
<table>
<tr>
<th>Pupil name</th>
<?php
$selectlesson=$connect->query("SELECT DISTINCT lessonid FROM `grades` ");
while($rowslesson=$selectlesson->fetch_array())
{
?>
<th><?php echo $rowslesson['lessonid']; ?></th>
<?php
}
?>
</tr>
<?php
$selectpupil=$connect->query("SELECT DISTINCT pupilid FROM `grades` ");
while($rowspupil=$selectpupil->fetch_array())
{
?>
<tr>
<td><?php echo $rowspupil['pupilid']; ?></td>
</tr>
<?php
}
?>
Thanks in advance for your help.
Actually I figured out how to do it. I repeated the SQL search in the TD and it seemed to work
<table>
<tr>
<th>Pupil name</th>
<?php
$selectlesson=$connect->query("SELECT DISTINCT lessonid FROM `grades` ");
while($rowslesson=$selectlesson->fetch_array())
{
?>
<th><?php echo $rowslesson['lessonid']; ?></th>
<?php
}
?>
</tr>
<?php
$selectpupil=$connect->query("SELECT DISTINCT pupilid FROM `grades` ");
while($rowspupil=$selectpupil->fetch_array())
{
?>
<tr>
<td><?php $pupil= $rowspupil['pupilid'];
echo $rowspupil['pupilid']; ?>
</td>
<?php
$selectlesson=$connect->query("SELECT DISTINCT lessonid FROM `grades` ");
while($rowslesson=$selectlesson->fetch_array())
{
?>
<td><?php $lessongrade = $rowslesson['lessonid'];
$selectgrade=$connect->query("SELECT * FROM `grades` where lessonid ='$lessongrade' and pupilid = '$pupil' LIMIT 1 ");
while($rowsgrade=$selectgrade->fetch_array())
{
echo $rowsgrade ['grade'];
}?>
</td>
<?php
}
?>
</tr>
<?php
}
?>
</tr>

How to dynamically split result into nested table

Hi I'm having trouble trying to split my db object result into the correct table for display.
Basically I'm trying to acheive this
<div class="panel"> $row->skill_group
<table class="collapse">
<thead>
<tr>
<th>$row->name</th>
</tr>
</thead>
<tbody>
<tr>
<td>$row->skill_name</td>
</tr>
<tr>
<td> $row->competency_name </td>
</tbody>
</table>
</div>
There can be many unique skill_groups and many skill_names but each person and their competency should only be displayed once for each skill.
My mysql returns the correct data however I can't figure out how to loop over the result so that I can split it in between the table that is nested from the div container.
For example the mysql result would be
======================================================================
| skill_group_name | skill_name | competency_name | name
======================================================================
| PHP Frameworks | Codeigniter | Working Knowledge | User name1
| PHP Frameworks | CakePHP | No Knowledge | User name1
| Database | T-SQL | Working Knowledge | User name2
======================================================================
and I need to fit it into the html structure above.
The result I'm after is
======================================================================
PHP Frameworks
======================================================================
| Codeigniter | Working Knowledge | User name1
| CakePHP | No Knowledge | User name1
======================================================================
Database
======================================================================
| T-SQL | Working Knowledge | User name2
======================================================================
I have managed to get the grouping of the skill_group sorted with:
if($row->skill_group_name != $skill_group_name)
{
echo '<div class="panel-heading"><a href="#" data-target=".skill'.++$counter.'" data-toggle="collapse">' . $row->skill_group_name;
$skill_group_name = $row->skill_group_name;
echo '</a></div>';
}
But I'm missing how to write the loops for the data table itself, how do I do this?
As I commented, I think you should save to an array, then implode() the sections:
//Just some fake data
$array[] = array('PHP Frameworks','Codeigniter','Working Knowledge','User name1');
$array[] = array('PHP Frameworks','CakePHP','No Knowledge','User name1');
$array[] = array('Database','T-SQL','Working Knowledge','User name2');
// Loop through the data
foreach($array as $row) {
// Save the table column html to array
$section[$row[0]][] = '<tr><td>'.$row[1].'</td><td>'.$row[2].'</td><td>'.$row[3].'</td></tr>';
}
// Loop through the section array you made
foreach($section as $title => $all) {
// Wrap it
echo '<div>'.$title;
// Implode
echo '<table>'.implode(PHP_EOL,$all).'</table>';
echo '</div>';
}

How to fetch multiple rows with same id from a table in zend framework?

Controller
public function detailsAction()
{
$this->getRequest()->isPost();
$pid = $this->getRequest()->getParam('pid');
$order =new Application_Model_DbTable_orders;
$this->view->orders = $order->fetchdetails($pid);
}
Model
public function fetchdetails($pid)
{
$select =$this->select()
->from('orderdetails')
->joinInner('products','products.id=orderdetails.productid')
->joinInner('suppliers','products.supplierid=suppliers.supplierid')
->where('pid = ?', $pid)
->setIntegrityCheck(false);
return $this->fetchAll($select);
}
Output
when I'm trying to fetch details of a particular PurchaseID i get the following result
| PurchaseID | ProductName | Price |Quantity |
| 100002346 | product 2 | 17765 | 5 |
| 100002346 | product 2 | 17765 | 2 |
| 100002346 | product 2 | 17765 | 2 |
in the above result set all the values except the ones in Quantity field is repeated.
This table is supposed to show 3 different products.
Here is my php code:
<?php foreach($this->orders as $ord) : ?>
<tr> <td>
<?php echo $this->escape($ord->productname);?>
</td> <td>
<?php echo $this->escape($ord->price);?>
</td> <td>
<?php echo $this->escape($ord->company);?>
<?php echo $this->escape($ord->url);?>
</td> <td>
<?php echo $this->escape($ord->Quantity);?>
</td> </tr>
<?php endforeach; ?>
,Please help me out people.

How to store an array in a database column

I have been trying to store an array in a database column, but haven't succeeded yet.
I have been looking into php and sql for two weeks now, and I don't have a programming background. So please forgive my ignorance. I'm sure I've made lot's of mistakes.
Let me explain my situation further.
I created a web page so a admin can fill in some data concerning some game. This is after a login process.
When a admin arrives at this point, I'm not bothering with 'correct' input at the moment. I just want to get the data in the db.
I created a table called games with mysql, and filled it with data I have so far:
+--------+--------+-----+-----+------+------+------+
|game_id |round_id|team1|team2|score1|score2|result|
+--------+--------+-----+-----+------+------+------+
| 1 | 1 | A | B | NULL | NULL | NULL |
| 2 | 1 | C | D | NULL | NULL | NULL |
| 3 | 1 | E | F | NULL | NULL | NULL |
| 4 | 2 | E | C | NULL | NULL | NULL |
| 5 | 2 | A | D | NULL | NULL | NULL |
| 6 | 2 | F | B | NULL | NULL | NULL |
+--------+--------+-----+-----+------+------+------+
Then I created a form in a php page which uses data from this table to display the teams per game.
The admin uses this form to fill in the game score and results. See the form below.This form is also needed to store values in the above table.
input.php
<?php
mysql_connect("xxx", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
$query="SELECT games_team1, games_team2 FROM games WHERE round_id = 1";
$result = mysql_query($query);
?>
<form action="someform.php" method="post">
<table id="inputgameresults">
<tbody>
<tr>
<th>Home</th>
<th>Score 1</th>
<th>-</th>
<th>Score 2</th>
<th>Away</th>
<th>Result</th>
</tr>
<?php while($row = mysql_fetch_array($result)) { ?>
<tr>
<td><?php echo $row['team1']; ?></td>
<td><input type="text" name="score1[]"/></td>
<td> - </td>
<td><input type="text" name="score2[]"/></td>
<td><?php echo $row['team2']; ?></td>
<td><input type="text" name="result[]"/></td>
</tr>
<?php } ?>
<tr>
<td></td>
<td</td>
<td</td>
<td</td>
<td</td>
<td><input type="submit" value="Submit"/></td>
</tr>
</tbody>
</table>
</form>
This results into 3 rows in the table in the form above. This table displays the teams for each match and input fields for the scores and the result.
A header, three rows with the games, input fields behind the games, and a sumbit button below.
A admin can submit the input with the form below. I added the echo so I can check if the output is correct. The echo works like a charm.
This is where things don't go the way I'd like them to go. The sql query I used is stated in the form. It fails miserably, probably because of my lack of knowledge.
form1.php
<?php
mysql_connect("xxx", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
$sc1 = $_POST['score1'];
$sc2 = $_POST['score2'];
$res = $_POST['result'];
foreach($sc1 as $value) {
echo "score team 1 $value<br/>";
mysql_query("UPDATE games SET game_score1 = '".$value[]"' WHERE games_id = [1,2,3] ");
}
foreach($sc2 as $value) {
echo "score team 2$value<br/>";
}
foreach($res as $value) {
echo "res $value<br/>";
}
?>
I'm sure there are a lot things besides the main issue I can improve, or do more efficient. Although this is not my main focus at the moment, any help is welcome :D
The main focus now is to get the input from the form in the right place in the db. The data from the form needs to be send to the database in columns score1, score2 and result for a game.
Any help or advice is most welcome!
a simple way to store a whole array in a database column is to encode the array to json ... in the example, $sc1 is the array you want to store
mysql_query("UPDATE games SET game_score1 = '". json_encode($sc1) . "' WHERE
games_id = [1,2,3,4,5,6,7,8,9] ");
then when you get your array from the colomnu, it is still on json format, so you need to do this
$array = json_decode($result);
sometimes your array contains elemens with '' all you need to do is to use
addslashes(json_encode($sc1))
instead of using
json_encode($sc1);
It looks like you just need the syntax to insert a new row to mysql. If game_id increments automatically, you don't have to specify it in the statment:
INSERT games (round_id, team1, team2, score1, score2, result)
VALUES (3, 4, 6, 18, 1, 0, 1);
In advance, thank you guys for the possible solutions to my problem. I'm definately gonna look into them.
A friend of mine told me that I should use a 'key' so that it would be able to loop in the database. Kinda like when the data was retreived from the database. This seemed to work.
I used a $key++ so it would start at the first games_id.
foreach($sc1 as $key => $value) {
$key++;
mysql_query("UPDATE games SET game_score1 = '".$value[]"' WHERE games_id = '".$key."' ");
}
My next challenge is to retreive per round_id and also store per round_id.
And to make it more interesting, the current date is gonna point to the current round_id :D

Get Hierarchical Data from Database

Hello i have one stupid question. But maybe is not.
In database i have table categories and i have 4 cols
Id, parent_id, title and description.
Parent_id is child of current category.
Id | parent_id | title | description
___________________________________________________
1 | 1 | Main Category | description
2 | 1 | Sub Category | description
3 | 2 | Other Category | description
4 | 1 | Some Category | description
Ok i know how to input data and show results; that is not problem. When i show result in table
<table>
<tr>
<td> Id </td>
<td> Parent </td>
<td> Title </td>
<td> Desc </td>
</tr>
<?php foreach($categories as $category): ?>
<tr>
<td> <?php echo $category->id; ?> </td>
<td> <?php echo $category->parent_id; ?> </td>
<td> <?php echo $category->title; ?> </td>
<td> <?php echo $category->eescription; ?> </td>
</tr>
<?php endforeach;?>
</table>
This works great and shows child categories under under the other parent categories : Table looks like this:
1 | 1 | Main Category | description
2 | 1 | Sub Category | description
3 | 2 | Other Category | description
4 | 1 | Some Category | description
My problem is how to list all category and sub category like this
|-- Main Category
|--- Sub Category
|--- One more cat
|--Other Category
|--- Some Category
Like this
Is it possible to fetch this data using forach() ? Any example how to do this.
Thanks
Read about this http://www.sitepoint.com/hierarchical-data-database-2/. Should solve your issue.
I do this. Am working on Codeigniter framework. If any need this i will post how i fix this like on screenshot.
Just simple make model :
Model
/*
* Get all children categories
*
* Get Hierarchical Data from Categories
*
* #ikac
*/
public function fetchChildren($parent, $level) {
$this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent='".$parent."' ");
foreach($this->handler->result() as $row) {
echo str_repeat(' |-----', $level).$row->title .'<br>';
$this->fetchChildren($row->title, $level+1);
}
}
}
Like output u will get
Default
|-----Sub Category
|-----Test Category 1
|-----Seccond Test Category 1
Thanks #Eugene

Categories