Incrementing child element database fetching in codeigniter - mysql

I'm trying to fetch a series of ids from a database table that includes cross-referencing - each element, a "topic", includes a column for "parent topic" that is within the same table. Given a single parent topic, I want to build an array of all the subtopics that have it as their parent, and then all of the subtopics of those topics, etc.
This doesn't seem like it's that hard, but as a self-taught programmer I feel I'm using all the wrong tools. The merge-array() and var_dump() sections, in particular, feel wrong and I'm not sure about the overall approach. What should I replace these elements with?
function get_subtopics($parent_topic)
{
//returns an array of subtopics minus the first
$all_subs = array();
$query = $this->db->get_where('topics', array('parent_topic' => $parent_topic));
$subs = $query->result_array();
$resubs = array();
$query->free_result();
//push subs to all_subs
//while the subs array has members, find their child
while (count($subs)>0) {
foreach ($subs as $s) {
$query = $this->db->get_where('topics', array('parent_topic' => $s['id']));
$resubs = array_merge($resubs, $query->result_array());
$query->free_result();
}
$all_subs = array_merge($all_subs, $resubs);
var_dump($resubs);
}
//Returns an array of ids
return $all_subs;
}
EDIT:
The objective of this is to form a "pool" of topics from which problems will be drawn for a random generator - I'm trying to get all of the subtopics into one array, with no tree structure to differentiate them. Users that specify a parent topic, like "math" should get an even mix of math subtopics like "algebra", "algebra:quadratics" or "calculus" from which problems will be drawn. Hope that clarifies a little.

There are 2 ways to do this either just get all the records from the database and build a tree structure using a php recursive function like below.
//Build menu array containing links and subs
$items = Array(
//highest level
'cms' => Array(
'title' => 'CMS',
//Array containing submenu items for cms
'subs' => Array(
'intro-to-cms' => Array('title' => 'Intro to CMS'),
'specific-cms' => Array('title' => 'Specific CMS'),
'installing-a-cms' => Array('title' => 'Installing a CMS')
),
)
);
//Display the menu
echo navlinks($items, $page);
/**
* Recursive function creates a navigation out of an array with n level children
* #param type $items
* #return string containing treestructure
*/
function navlinks($items, $page=false)
{
$html = '<ul>';
foreach ($items AS $uri => $info) {
//Check if the pagename is the same as the link name and set it to current when it is
$html .= '<li'.($info['title'] == $page ? ' class="current"' : '').'>';
echo ' ' . $info['title'] . '';
//If the link has a sub array, recurse this function to build another list in this listitem
if (isset($info['subs']) && is_array($info['subs'])) {
$html .= navlinks($info['subs']);
}
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
In order to just filter on 1 parent with its underlying children you will need a rather tricky query in advance like explained in a previous comment on stackoverflow. (link below)
MySQL parent -> child query

Related

Retrieve every model and return three values

I am looking for a way to retrieve all models in a database. Then loop through all of the models and read out the values for name, firstname and phonenumber.
So far I've gotten this and failed to go past it:
$searchModel = new EmployeeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
I am then looking to implement those three values in a simple HTML table:
<tr><td>$firstname</td><td>$name</td><td>$phone</td></tr>
The table should be part of a PDF output, so ideally I would save it to a variable:
$html_table = '<tr><td>$firstname</td><td>$name</td><td>$phone</td></tr>';
I would need to get this for every model that fulfills the criteria of status = 'active' in the database.
So far I've only been able to get tables via gridView and not in a HTML template either.
You don't really need a data provider to achieve this, you could simply try :
$models = Employee::find()->where(['status'=>'active'])->orderBy('name ASC')->all();
foreach ($models as $model) {
echo "<tr><td>{$model->firstname}</td><td>{$model->name}</td><td>{$model->phone}</td></tr>";
}
Read more : http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#querying-data
You can get all models like this:
$employees = Employee::find()
->select('firstname, name, phone')
->asArray()
->where(['status'=>'active'])
->all();
This way you will get an array of arrays containing the 3 selected fields, so now you only need to use a foreach to loop through them and create the table:
$html = '<table>';
foreach($employees as $employee) {
$html .= '<tr><td>'.$employee['firstname'].'</td><td>'.$employee['name'].'</td><td>'.$employee['phone'].'</td></tr>';
}
$html .= '</table>'

syntax for accessing hash param in hash of hashes when using foreach

I've got this hash of hashes and I'm trying to populate a select box with values from each hash. Anyway I'm having trouble getting to my inner hash variables. I am able to generate the right number of options in my select, but I'm currently only able to set the value parameter of each select option.
Heres my hash:
my $export_types = { a => {label => "Foo", ext => ".js"},
b => {label => "Bar", ext => ".gz"}};
Heres what I've tried so far for my foreach:
my $select = "<select id='fancy'>";
foreach my $key (sort keys %{$export_types})
{
$select .= "<option value='$key' ";
if($saved_value eq $key || (!$saved_value && $key eq "a"))
{
$select .="selected='selected'";
}
$select .= ">".$export_types{$key}{label}."</option>";
}
$select .= "</select>";
apparently I'm accessing the label property wrong. For that particular line I also tried:
$select .= ">".$export_types{$key}->{label}."</option>";
but that was to no avail as well. I'm sure I'm missing something simple.
Thanks for the help :)
The expression
$export_types{$key}{label}
assumes that there is a hash %export_types. This is not the case. If you had a use strict in scope, you would have been alerted to this fact.
Because $export_types is a hash reference, we have to dereference it before using the subscript operator to access some value. Either
$export_types->{$key}{label}
or
$$export_types{$key}{label}
(I prefer the former).

Parsing External Table Arguments in Wordpress

I have a client project that has posts assigned to their country of origin.
The client wants to be able to search the posts by continent and or region.
I have a separate table that assigns each country to its respective region, and I have the WP query that uses the resulting array:
$country_names = array('England','France','Germany',...); // this would be the result from fetching countries associated with a region.
$args = array(
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'country',
'value' => $country_names,
'compare' => 'IN'
)
)
);
$query = new WP_Query( $args );
What I'm having trouble with is the part in the middle. Normally, I'd use some standard PHP/MySQL to craft the array:
<?php
//Process incoming variable
if(!empty($_REQUEST['region'])){
$region = $_REQUEST['region'];
} else {
$region = NULL;
}
// Make a MySQL Connection
$query = "SELECT * FROM regions WHERE region='$region'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['country'];
?>
However, I'm having trouble making it work within a WP template, since WP manages the incoming variables using its own internal functions.
Can anyone help me to connect the two together? I'm sure I'm overlooking some simple step here, or else I'm not using some built-in WP function.
Any help is appreciated.
Thanks!
ty
Add this in your functions.php
add_filter( 'query_vars', 'addnew_query_vars', 10, 1 );
function addnew_query_vars($vars)
{
$vars[] = 'region'; // region is the variable you want to add
$vars[] = 'anotherVar';
return $vars;
}
Then get it
$region=get_query_var('region')
Update
$regions = $wpdb->get_results("SELECT ".$region." FROM `".$wpdb->regions."`");
if($regions)
{
foreach($regions as $region)
{
// your code
}
}

Filtering theme_table in Drupal

I just created a data table based on a query and displayed it successfully using theme_table().
Now, I'd like to add some filters to the table but have no idea how to proceed.
Is there a built-in feature that allow me to do this easily, or should I manually add a form and update the query/redisplay the results each time the user selects something?
Thanks for your help!
I think you want to use pager_query and tablesort_sql: it's especially made for creating tables of data with pagination and sorting capabilities (and themes usually theme such tables nicely out of the box).
Example:
<?php
// The regular query without sorting or pagination parameters
$sql = 'SELECT cid, first_name, last_name, company, city FROM {clients}';
// Number of rows per page
$limit = 20;
// List of table columns ("field" is the matching database column from the sql query)
$header = array(
array('data' => t('Name'), 'field' => 'last_name', 'sort' => 'asc'),
array('data' => t('Company'), 'field' => 'company'),
array('data' => t('City'), 'field' => 'city')
);
// Calculates how to modify the SQL query according to the current pagination and sorting settings
// Then performs the database query
$tablesort = tablesort_sql($header);
$result = pager_query($sql . $tablesort, $limit);
$rows = array();
while ($client = db_fetch_object($result)) {
$rows[] = array(l($client->last_name.', '.$client->first_name, 'client/'.$client->cid), $client->company, $client->city);
}
// A message in case no results were found
if (!$rows) {
$rows[] = array(array('data' => t('No client accounts created yet.'), 'colspan' => 3));
}
// Then you can pass the data to the theme functions
$output .= theme('table', $header, $rows);
$output .= theme('pager', NULL, $limit, 0);
// And return the HTML output
print $output;
?>
(I added comments, but the original version of the example comes from this page)
Alternatively, maybe you don't need to make a module at all if you're just trying to make a page that displays a list of data, you may prefer using the Views module.

Retrieving widget data with MySQL query in WordPress

I've built up multiple dynamic sidebars for front page item manipulation. Each sidebar contains a Text widget, and I want to retrieve each widget's content (according to widget ID) from wp_options.
Basically, the structure is dbName -> wp_options -> option_id #92 contains the following:
a:9:{i:2;a:0:{}i:3;a:3:
{s:5:"title";s:0:"";s:4:"text";s:2:"mainItem";s:6:"filter";b:0;}i:4;a:3:
{s:5:"title";s:0:"";s:4:"text";s:9:"leftThree";s:6:"filter";b:0;}i:5;a:3:
{s:5:"title";s:0:"";s:4:"text";s:10:"rightThree";s:6:"filter";b:0;}i:6;a:3:
{s:5:"title";s:0:"";s:4:"text";s:8:"rightTwo";s:6:"filter";b:0;}i:7;a:3:
{s:5:"title";s:0:"";s:4:"text";s:8:"rightOne";s:6:"filter";b:0;}i:8;a:3:
{s:5:"title";s:0:"";s:4:"text";s:7:"leftOne";s:6:"filter";b:0;}i:9;a:3:
{s:5:"title";s:0:"";s:4:"text";s:7:"leftTwo";s:6:"filter";b:0;}
s:12:"_multiwidget";i:1;}
[Actually all on one line.]
I want to retrieve the following strings:
mainItem
leftOne/leftTwo/leftThree
rightOne/rightTwo/rightThree
What's the syntax for such a query? And how can I add it to the PHP template?
You can pull all of the information about a type of widget from the database like so:
$text_widgets = get_option( 'widget_text' );
There's no need to use mySQL to get this. This will return an array of all the stored widgets of the type 'text'. Then you can loop through this array and do stuff with the internal properties of each like so:
foreach ( $text_widgets as $widget ) {
extract( $widget );
// now you have variables: $mainItem, $leftOne, $leftTwo, etc.
// do something with variables
}
Or, if you already know the ID's of the widgets you want to interact with, you can access the properties like this:
$mainItem = $text_widgets[17]['mainItem'];
Try below code snippet. It return the array of all widgets stored data.
// 1. Initialize variables
$data = '';
$all_stored_widgets = array();
// 2. Get all widgets using - `$GLOBALS['wp_widget_factory']`
$all_widgets = $GLOBALS['wp_widget_factory'];
foreach ($all_widgets->widgets as $w => $value) {
$widget_data = get_option( 'widget_' . $value->id_base );
foreach ($widget_data as $k => $v) {
if( is_numeric( $k ) ) {
$data['id'] = "{$value->id_base}-{$k}";
$data['options'] = $v;
$all_widgets_css[$value->id_base][] = $data;
}
}
}
// 3. Output:
echo '<pre>';
print_r( $all_stored_widgets );
echo '</pre>';
Output: