Create Unordered List from View Query? - php

I have a query that will produce the results I need:
SELECT SHOW_NAME, YEAR, CLASS_NAME FROM vwhandlerresults WHERE HANDLER_ID = $gethandlerid ORDER BY YEAR DESC
SHOW_NAME YEAR CLASS_NAME
Show 1 2013 Class 1
Show 1 2013 Class 2
Show 2 2013 Class 1
Show 3 2012 Class 1
etc. etc.
I want to create a 3 level unordered list in php so that I can have something similar to the following:
2013
Show 1
Class 1
Class 2
Show 2
Class 1
2012
Show 3
Class 1
I have searched and searched, and can't get my head around it at all. I managed it to one level (Year -> Show). From searching, I get the feeling I might need an array?
Thanks
Gray

Technically, you don't need to build an array in advance. You can do it as the data is fetched from the DB using a simple-ish "state machine".
echo '<ul>';
$oldyear = null;
$oldshow = null;
while($row = fetch_result($result)) { // grab a row of DB data
if ($oldyear != $row['year']) {
echo "<li>{$row['year']}<ul>";
}
if ($oldshow != $row['show']) {
echo "<li>{$row['show']}<ul>";
}
echo "<li>{$row['class']}</li>";
}
NOTE: this will NOT work as is, it's just to give you a general idea of what'd be needed if you choose to go this route
However, if you choose to go with the array route, it'll be a bit more work upfront, but vastly simplify the output logic:
$data = array();
while($row = fetch_row($result)) {
$year = $row['year'];
$show = $row['show'];
$data[$year][$show][] = $row['class'];
}
echo '<ul>'
foreach($years as $year => $shows) {
echo '<li>', $year, '<ul>';
foreach($shows as $show) {
echo '<li>$show<ul>';
foreach ($show as $class) {
echo '<li>', $class, '</li>';
}
echo '</ul>';
}
echo '</ul>';
}
echo '</ul>';

Related

Getting total count of nodes in tree

I am creating a simple Affiliate System (5 Level max). So basically the database have this kind of structure:
"aff level" column is just extra things so that i know that i listed out correctly.
I have successfully listed out (in bullet format) the parent & child of each agent. Below is my code:
function list_current_agents($aff_parent_id, $aff_level){
$max_level = 5;
if($aff_level <= 5)
{
$query = "SELECT aff_id, agent_code FROM affiliate WHERE aff_parent_id = '$aff_parent_id' AND aff_level = '$aff_level'";
$result = db_query($query);
$row = $result-> fetch_object();
if($result-> num_rows > 0)
{
echo '<ul>';
do{
$aff_id = $row-> aff_id;
$agent_code = $row-> agent_code;
echo '<li>';
echo $aff_id .' - '.$agent_code . ' - (level '.$aff_level.')';
echo '</li>';
$aff_level = $aff_level+1;
if($aff_level <= 5)
{
list_current_agents($aff_id, $aff_level+1);
}
}while($row = $result-> fetch_object());
echo '</ul>';
}
}
return $count;
}
and the output will be like this:
And now im stucked where i want to list out the total number of the child below if i select one of the parent agent. For example, if i select:
Agent1
total child : 8
Agent3
total child : 3
I have tried any method i can think of but cant work out with the logic.
Any help is very much appreciated.
thanks in advance.
Create an actual tree data structure and it will be easy to count the children.
Or you can use one of the many available on Github. This one is even made for you specific database structure.

Accessing results from collect() using neo4j-php-client

The below displays:
Marlena has 12 paintings (which is basically from the docs)
How do I access the data in collect(Paintings)
ex: title
$query = "MATCH (n:Artist)-[:PAINTED]->(Painting) RETURN n.first_name, collect(Painting) as paintings";
$result = $client->run($query);
foreach ($result->getRecords() as $record) {
echo sprintf('%s has %d paintings', $record->value('n.first_name'), count($record->value('paintings')));
echo '<br/>';
}
I would like to display:
Artist Name:
painting title
painting title
etc
I assume this data can be pull from either Painting or paintings. I am just unsure how to put together the query. It will display using print_r and the record so I know the data is coming through.
This should work for you:
$query = "MATCH (n:Artist)-[:PAINTED]->(Painting) RETURN n.first_name, collect(Painting) as paintings";
$result = $client->run($query);
foreach ($result->getRecords() as $record) {
echo sprintf('%s has %d paintings:<br/>', $record->value('n.first_name'), count($record->value('paintings')));
foreach ($record->value('n.paintings') as $painting) {
echo sprintf('- %s<br/>', $painting->value('title'));
}
echo '<br/>';
}
a) I suggest you alias your return values, it is easier to fetch them at the driver level
b) The paintings record value returns an array of Node objects, thus is iterable, no need to count for doing the for loop :
$query = "MATCH (n:Artist)-[:PAINTED]->(Painting) RETURN n.first_name as firstName, collect(Painting) as paintings";
$result = $client->run($query);
foreach($result->records() as $record) {
echo sprintf('%s painted %d paintings', $record->get('firstName'), count($record->get('paintings'))) . PHP_EOL;
foreach ($record->get('paintings') as $painting) {
echo sprintf('%s - %d views', $painting->value('title'), $painting->value('views')) . PHP_EOL;
}
}
I ended up getting it to work with the following:
foreach ($result->getRecords() as $record) {
$fname = $record->values()[0]->get('first_name');
$lname = $record->values()[0]->get('last_name');
echo '<strong>'.$fname.' '.$lname.' painted:</strong><br/>';
for ($x = 0; $x < count($record->values()[1]); $x++) {
print_r($record->values()[1][$x]->get('title'));
echo ' - ';
print_r($record->values()[1][$x]->get('views'));
echo ' views<br/>';
}
echo '<br/>';
}
Which provides the following output:
First Name Last Name painted:
Lumine - 86 views
Pooled Water - 69 views
Still Lake - 125 views
Final Notes
I actually tried code similar to what you suggested during my struggle to get this working. I'm a bit confused why it does not.
So I'm left wondering. Is what I come up with acceptable?

Show number of factories behind categories in sidebar. codeigniter

I have a sidebar with categories. when i click on one categorie it shows me the factories who are located in that category.
I did this using joins in codeigniter.
Now i want to show how much factories are in a category. so for example:
Categories.
Cars (2)
Books (7)
Animals (45)
So it simple has to show how much factories have that specific category.
i tried to do a simple count_all_results but then i get the total count of factories. but i want them to count by the specific id of categories.
my model function:
function categorieen_getall($segment3)
{
$this->db->where('categorieen.idcategorieen', $segment3);
$this->db->select('*');
$this->db->from('bedrijfcategorieen');
$this->db->join('categorieen', 'categorieen.idcategorieen = bedrijfcategorieen.idcategorieen');
$this->db->join('bedrijven', 'bedrijven.idbedrijven = bedrijfcategorieen.idbedrijven');
$query = $this->db->get();
$result = $query->result();
/*
echo '<pre>';
print_r($result);
*/
return $result;
}
My controller function:
function get_All()
{
$data['cat'] = $this->categorieen_model->categorieen_getall($segment3);
$this->load->view('views/sidebar', $data);
}
My view:
<div id="sidebar">
<?php
echo '<h3>Categorieën</h3>';
echo ($this->db->count_all_results('categorieen'));
?>
<hr>
<br/>
<?php
echo '<ul>';
if(isset($cat) && is_array($cat)){
foreach($links as $k => $value){
echo '<li>';
echo '<br>';
echo '' .$value->Categorie. '';
echo '</li>';
}
}
echo '<ul>';
/*
if(isset($cat ) && is_array($cat )){
foreach($cat as $key => $row){
echo "Categorie:"; echo $row->Categorie;
echo "<br />";
echo $row->idcategorieen;
echo "<br />";
echo $row->Bedrijfsnaam;
}
}
*/
?>
</div>
My database scheme:
Factories
--------
idfactories
factoryname
adress
email
...
Categories
----------
idcategories
Category
Factorycategories
-----------------
idfactorycategories
idcategories
idfactories
This is not quite suitable because I know there is a better way to do this, but this will do the work for you:
// Get categories
$categories = array();
$query = $this->db->query("select * from `Categories` order by `idcategories`");
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
$query_count = $this->db->query("select `idfactorycategories` from `Factorycategories` where `idcategories` = {$row['idcategories']}");
$factory_count = $query_count->num_rows();
$categories[] = array(
'count' => $factory_count
);
}
}
For ease, you can first get categories in a foreach loop and then for each of them submit a query for the factories table to get relevant count of factories with that related category id.
I asked another question. with the same problem and i solved it.
Look at my own answer with the solution i got!
Count results in joined table and show between () in sidebar
Thanks for the people who helped me :)

PHP how to echo the first value of each group in a mysql query list

To better explain my situation, please take a look at this mokeup query result:
Category Item
cat1 Item 1
cat1 Item 2
cat1 Item 3
cat23 Item x
cat23 Item y
cat23 Item z
X apples
X oranges
X bananas
and so on....
I am pulling the data off a mysql database and would like to display the results like this:
Category----Item
cat1 Item 1
Item 2
Item 3
cat23 Item x
Item y
Item z
X apples
oranges
bananas
and so on....
I tried different ways but I am coming up empty. This is the latest attempt:
PHP
//Headers
echo 'Category';
echo ' | ';
echo 'Item';
echo "\n";
$sql = "SELECT `table1`.*, `table2`.* FROM table1 INNER JOIN table2 ON `table1`.`Category` = `table2`.`Category` ORDER BY `table1`.`Category`, `table2`.`Item`";
$dbq = mysql_query( $sql );
$cat = '';
while( $data = mysql_fetch_assoc( $dbq ) ) {
if( !$cat == $data['category'] ) {
$cat = $data['category'];
echo $cat;
echo ' | ';
echo $data['item'];
echo "\n";
}
else {
echo ' ';
echo ' | ';
echo $data['item'];
echo "\n";
}
}
With this code, the current output is:
Category----Item
cat1 Item 1
Item 2
Item 3
Item x
Item y
Item z
apples
oranges
bananas
...rather than the desired output.
I am looking for the most efficient and simple way to echo each category 1 time only. Perhaps this code is not the best way to approach it, but I tried in different ways and my brain right now is shut S_S .
Took me quite some time...
Change
if( !$cat == $data['category'] ) {
To
if( $cat != $data['category'] ) {
Better to concatenate the Items of same category and store it like as Item1,Item2,Item3.
When you want to use this Items use explode() to split and
when ever you want to search in this items for a particular item use mysql's FIND-IN-SET
Not sure what you're looking for as that solution seems like it solves what you need it to do but if you want to be more tolerant of the result orders you can try this:
$concated_data = array();
while( $data = mysql_fetch_assoc( $dbq ) )
{
if ( ! array_key_exists( $data['category'], $concated_data ) )
$concated_data[$data['category']] = array();
array_push($concated_data[$data['category']], $data['item']);
}
foreach ($concated_data as $category => $items)
{
echo $category;
$count = count($items);
for ($i = 0; $i < $count; $i++)
{
if ($i == 0)
echo "\t";
else
echo "\t\t";
echo $items[$i]."\n"; // Items
}
}
Formatting up to you at this point I guess but I think putting the data into an array of arrays is the best way so the top level keys are categories and then the arrays they point to now hold an array of your items. This also doesn't assume that you get results in the same category consecutively.
Sorry code might contain bugs as I haven't coded in PHP in awhile. But basically you should accumulate the items first then go through the accumulated list and output the data.

Recursive tree traversal with mysql through PHP

I am creating a questionnaire for a client that requires the questions to be organized by 3 layers of levels. I've successfully created the U.I. however I've been trying for the last 3 hours to pull data from a database in such a way that everything loads in the right place. The database is organized like so by the client so I have no control over it:
id description parentId
1 Level 1 0
2 Level 2 0
3 Level 1a 1
4 Level 1b 1
5 Level 1a1 3
I have found a similar question to mine on the site but when I attempted it's solution I got the following on repeat infinetly:
Code:
function makeList($par_id = 0) {
//your sql code here
$result = mysql_query("SELECT * FROM pB_test WHERE parentId = $par_id");
$pages = mysql_fetch_array( $result );
if (count($pages)) {
echo '<ul>';
foreach ($pages as $page) {
echo '<li>', $page['description'];
makeList($page['parentId']);
echo '</li>';
}
echo '</ul>';
}
}
makeList();
Output:
1
3
5
5
l
l
3
5
5
l
l
3
5
5
l
l
3
5
5
l
l
Does anyone know how to fix this and what the issue is exactly? Cheers
it's not good to call mysql server and fetch result each time
what if you have over 100 rows? or 200+
use this to query only once:
$result = mysql_query("SELECT * FROM test");
$arrs = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$arrs[] = $row;
}
function build_tree($arrs, $parent_id=0, $level=0) {
foreach ($arrs as $arr) {
if ($arr['parent_id'] == $parent_id) {
echo str_repeat("-", $level)." ".$arr['name']."<br />";
build_tree($arrs, $arr['id'], $level+1);
}
}
}
build_tree($arrs);
common example for table
id name parent_id
Do this recursivly:
function printChildQuestions($parentid) {
$sql="SELECT * FROM pB_test WHERE parentID=$parentid";
$result=mysql_query($sql);
$i=0;
while (true) {
$row=mysql_fetch_array($result);
if (!$row) break;
if ($i==0) echo "<ul>";
$i=1;
echo '<li>'.$row['id'].' '.$row['description'].' '.$row['parentId'].'</li>';
printChildQuestions($row['id']);
}
if ($i>0) echo '</ul>';
}
printChildQuestions(0);

Categories