How to dynamically split result into nested table - php

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

Related

API-call JSON into MySQL

I'm working on a research project where we want to insert a JSON file (from an API-call) into a mysql database. I found multiple examples but I don't know where to begin because there are multiple objects and arrays. A second problem is that the columns and rows are separate arrays (I think?).
Our goal is to fill (daily, hourly, etc) a database that looks likes this (it is an example and we do have multiple items):
-----------------------------------
| Date | Value2 | Value3 | Value4 |
-----------------------------------
| 01-01-2015 | 123 | 1234 | 12345 |
-----------------------------------
| 02-01-2015 | 343443 | 4w3543422 | fref4rw4 |
-----------------------------------
| 03-01-2015 | 234422r | wrfrw3434 | 2432rfr42324 |
-----------------------------------
Question is how can I get those values from the JSON (which isn't static: sometimes there will be seven days, sometimes less and sometimes more)? Where to begin?
Code from #Marmik did the trick!
<?php
$array = json_decode($json_data,true);
$sql_inserts = array();
foreach($array['reportitem']['rows']['r'] AS $row)
{
$sql_inserts[] = "('".$row[c][0]."','".$row[c][1]."','".$row[c] [2]."','".$row[c][3]."')";
}
$insert_values = implode("'",$sql_inserts);
$sql = "INSERT INTO table_name (date,Value2,Value3,Value4) $insert_values ;";
?>
I think using foreach loop after decoding the JSON to PHP Array it can be worked out.
<?php
$array = json_decode($json_data,true);
$sql_inserts = array();
foreach($array['reportitem']['rows']['r'] AS $row)
{
$sql_inserts[] = "('".$row[c][0]."','".$row[c][1]."','".$row[c][2]."','".$row[c][3]."')";
}
$insert_values = implode("'",$sql_inserts);
$sql = "INSERT INTO table_name (date,Value2,Value3,Value4) $insert_values ;";
?>
And this SQL statement is created by JSON array's data.

Present one bulleted list for each row in a MySQL table

I have a mysql table like this:
name1 | dllink1 | dltarget1 | dllink1Text | link2 | dltarget2 | dllink2Text | link3 | dltarget3 | dllink3Text | ... | link10
name2 | dllink1 | dltarget1 | dllink1Text | link2 | dltarget2 | dllink2Text | NULL | NULL | NULL | ... | link10
... | ... | ... | ... | ... | ... | ... | ... | ...
I want to output a bulleted list of the links for each of the names as long as the link is not NULL:
<dl>name1<dl/>
<li><a href="dllink1" target="dltarget1>dllink1Text</a></li>
<li><a href="dllink2" target="dltarget2>dllink2Text</a></li>
<li><a href="dllink3" target="dltarget2>dllink3Text</a></li>
<dl>name2<dl/>
<li><a href="dllink1" target="dltarget1>dllink1Text</a></li>
<li><a href="dllink2" target="dltarget2>dllink2Text</a></li>
<dl>name3<dl/>
<li><a href="dllink1" target="dltarget1>dllink1Text</a></li>
...
('dltarget(x)' is _self, _blank etc. in the table)
What is the best and most correct approach to achieve this? Fetching values, i.e. $row['name'] in a while($row = #mysql_fetch_array($rs)) is relatively easy for a novice to learn, but this turned out somewhat of a challenge..
First off your SQL table is not properly normalized. You should split it out into two tables (this will make it far easier to extend, maintain and understand) - say links and link_groups (for the sake of argument since I am not totally aware of the context). Your links table can contain "href", "target", "title" and "link_group_id" as the foriegn key to associate your link with your link_group and your link_groups can have an auto incremented "id" as the primary key and a "name" field to identify the group.
There are a number of ways to approach the problem once this has been done and one simple (albeit a little noisy) approach would be as follows...
Note, the alternative PHP syntax in second block (this is assuming front end code). You can code it however you like - (i.e. put PHP in traditional form in one entire block).
<?php
$links = []; // only use this alternative array syntax if using PHP 5.4+
// your recordset for links
while ($row = mysql_fetch_object($rs)) {
$links[$rs->link_group_id][] = $row;
}
?>
<!-- your recordset for link groups -->
<?php while ($row = mysql_fetch_object($rs)): ?>
<dl>
<dt><?php echo($row->name); ?></dt>
<?php foreach ($links[$row->id] as $link): ?>
<dd>
<a href="<?php echo($link->href); ?>"
target="<?php echo($link->target); ?>"><?php echo($link->title); ?></a>
</dd>
<?php endforeach; ?>
</dl>
<?php endwhile; ?>

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

dynamically build both <th>'s and <tr>'s

The amount of columns in a table is based upon the amount of data in a table. The amount of rows in a table is based on the amount of rows in a different table. An example of these tables are below
environments patches
id | name id | name
____|______ ____|____________
1 | dev 1 | firstPatch
2 | test 2 | secondPatch
3 | prod 3 | thirdPatch
The end result of what I'm looking for would be the following <table>
_________________________________
| Patch Name | dev | test | prod |
|_____________|_____|______|______|
| thirdPatch | | | |
| secondPatch | x | | |
|_firstPatch__|_____|______|______|
I understand how I could use a while() loop to build the table headers. And I understand how I could use a while() to build the rows.
echo "<tr>";
while ($env = $listEnvs->fetch_assoc()){
echo "<th>".$env['name']."</th>"
}
echo "</tr>";
--AND--
while ($patch = $listPatches->fetch_assoc()){
echo "<tr><td>".$patch['name']."</td></tr>";
}
What I am struggling with is that the cells for each patch/environment pair are going to have data that is pulled from several other tables. So knowing the patch.id as well as the environment.id is important. Example the cell with the x is patch.id = 2, environment.id = 1 When constructing the table, how can I make sure each cell has this necessary information?
Try to create an array like $content[$patch.id][$environment.id].
Then you can add echo($content[$patch.id][$environment.id]) to your while of the $patch. You walk through the patches, so $patch.id is known. For $environment.id, you should make an array with all environment.id's and walk through it with $environment.id[i], where $i should be increased with each new column (and set to 0 when a new row is started).
In (bad) pseudo-code:
walkthrough environments {
save array with environments
echo table headers
}
walk through patches {
echo table 'row headers'
walk through environment array {
echo content[patch.id][environment.id]
}
}

Navigate through tables with zend framework

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.

Categories