I am having difficulty conceptualizing a recursive function for appending replies to comments, replies to replies, replies to replies to replies, etc.
This is my comments table:
Which SHOULD look something like this when rendered:
As it stands I can render each comment associated with the article_id (excluding those that are NOT NULL, of course):
$comments = $commentClass->fetch_article_comments($article_id);
foreach($comments as $comment) {
$comment_id = $comment['comment_id'];
$member_id = $comment['member_id'];
$comment_text = $comment['comment_text'];
$comment_timestamp = timeAgo($comment['comment_timestamp']); //get time ago
//render comment using above variables
}
Now I'm assuming I need to add a recursive function at the end of the above foreach statement, but I have yet to come up with anything remotely successful in appending the comments replies and the replies to each reply.
Can anyone help me accomplish this or perhaps point me in the right direction. I am not entirely familiar with recursive functions. I have done some scanning of the internet and on stackoverflow looking for something that helps, but haven't found anything helpful yet.
I did come across this post which recommended using a hierarchical database system, but I think I would prefer to use a php recursive function for this.
Thanks.
edit
By using the below answers I am only returning the results first comment and then it iterates and displays that one comment indefinitely. I can't figure out why?
My php:
function display_comments($article_id, $parent_id=0, $level=0) {
global $comment;
global $member;
global $signed_in;
global $username;
$comments = $comment->fetch_article_comments($article_id, $parent_id);
foreach($comments as $data) {
$comment_id = $data['comment_id'];
$c_member_id = $data['member_id'];
$comment_text = $data['comment_text'];
$comment_timestamp = timeAgo($data['comment_timestamp']); //get time ago
$member_data = $member->fetch_member_data($c_member_id);
$c_member_username = $member_data['member_username'];
$c_member_avatar = $member_data['member_avatar'];
//render HTML here
$parent = $data['comment_parent'];
display_comments($article_id, $parent, $level+1);
}//end foreach
}//end display_comments()
and my PDO query:
public function fetch_article_comments($article_id, $parent_id) { //$page = (int)(!isset($_GET['page'])) ? 0 : $_GET['page'];
if ($parent_id > 0) {
$parent_id = "= $parent_id";
} else {
$parent_id = "IS NULL";
}
$query = $this->db->prepare("SELECT * FROM `comments2` WHERE `article_id` = $article_id AND `comment_parent` $parent_id ORDER BY `comment_timestamp` DESC");
try{
$query->execute();
$comments = $query->fetchAll(); //returns an array
$query->closeCursor();
return $comments;
} catch(PDOException $e){
die($e->getMessage());
}
}
The core of the problem is this:
$comments = $commentClass->fetch_article_comments($article_id);
I assume, this function somwhere creates and runs SQL, that is similar to SELECT ... WHERE comments.article_id=$article_id. This is not sufficient - you need something like
$comments = $commentClass->fetch_article_comments($article_id, $parent_id);
that translates into SQL similar to SELECT ... WHERE comments.article_id=$article_id AND comments.comment_parent ($parent_id>0)?"=$parent_id":"IS NULL"
Now you can write your PHP function:
function display_comments ($article_id, $parent_id=0, $level=0) {
$comments = $commentClass->fetch_article_comments($article_id, $parent_id);
foreach($comments as $comment) {
$comment_id = $comment['comment_id'];
$member_id = $comment['member_id'];
$comment_text = $comment['comment_text'];
$comment_timestamp = timeAgo($comment['comment_timestamp']); //get time ago
//render comment using above variables
//Use $level to render the intendation level
//Recurse
display_comments ($article_id, $comment_id, $level+1);
}
}
And finally call it with display_comments ($article_id);
You could do something like:
function getCommentsForParent($parent="") {
echo "<div class=\"comment\">";
$db = get("select your db logics where parent = $parent");
foreach ($db as $comment) {
echo "print your comment in a box and make a div around the hole comments"
getCommentsForParent($comment['parent_id']);
}
echo "</div>";
}
invoke function with getCommentsForParent()
With your code it should be something like:
function getCommentForParent($parent="") {
global $commentsClass, $article_id;
$comments = $commentClass->fetch_article_comments($article_id,$parent);
foreach($comments as $comment) {
$comment_id = $comment['comment_id'];
$member_id = $comment['member_id'];
$comment_text = $comment['comment_text'];
$comment_timestamp = timeAgo($comment['comment_timestamp']); //get time ago
getCommentForParent($comment['parent']);
}
}
Look closely, ive adjusted your fetch article_comments. It now has a listener for $parent. Make sure that when your $parent = "", the class will only select the comments with empty parent.
invoke with getCommentsForParent()
It will automatically loop through the parent. Ofcourse this is highly conceptual but given your code you should get the hang of it.
Related
I have class called posts in a separate file :
<?php
class POSTS {
//Start of class properties:
private $db_connection;
public $post_id;
public $section_id;
public $user_id;
public $post_title;
public $post_details;
public $post_date;
public $post_category;
public $post_display;
public $num_of_rows;
public function getRelatedPosts($section_name, $category, $display) {
$stm = $this->db_connection->prepare("SELECT * FROM posts WHERE section_name!=:Section_name AND category=:Category AND display=:Display ORDER BY id DESC");
$stm->bindParam(":Section_name", $section_name);
$stm->bindParam(":Category", $category);
$stm->bindParam(":Display", $display);
$stm->execute();
$this->num_of_rows = $stm->rowCount();
if ($this->num_of_rows >= 1) {
$post_data = $stm->fetch(PDO::FETCH_OBJ);
$this->post_id = $post_data->id;
$this->section_id = $post_data->section_id;
$this->user_id = $post_data->user_id;
$this->post_title = $post_data->title;
$this->post_details = $post_data->details;
$this->post_date = $post_data->date;
$this->post_category = $post_data->category;
$this->post_display = $post_data->display;
}
}
}
?>
Then I want to loop through the results in my Index file:
$section_name = 'PHP';
$display = 'yes';
$POSTS->getRelatedPosts($section_name, $category $display);
$num_of_rows = $POSTS->num_of_rows;
if ($num_of_rows >= 1) {
for ($m=1; $m<=$num_of_rows; $m++) {
$post_id = $POSTS->post_id;
$section_id = $POSTS->section_id;
$user_id = $POSTS->user_id;
$post_title = $POSTS->post_title;
$post_details = $POSTS->post_details;
$post_date = $POSTS->post_date;
?>
<div id="related_post">
<h4><?php echo $post_title;?></h4>
<p><?php echo $post_details;?></p>
</div>
<?php
}
} else {
echo 'Sorry no related posts now!';
}
Unfortunately The results are only one record repeated as many as the $num_of_rows variable equal.
I tried some different ways with fetch methods like:
fetchAll() and others styles but always the result is an error or only one record repeated.
Someone help me with my code please.
If you want to loop, try looping in your method:
public function getRelatedPosts($section_name, $category, $display)
{
$stm = $this->db_connection->prepare("SELECT * FROM posts WHERE section_name!=:Section_name AND category=:Category AND display=:Display ORDER BY id DESC");
$stm->bindParam(":Section_name", $section_name);
$stm->bindParam(":Category", $category);
$stm->bindParam(":Display", $display);
$stm->execute();
$this->num_of_rows = $stm->rowCount();
if ($this->num_of_rows >= 1) {
while($post_data = $stm->fetch(PDO::FETCH_OBJ)) {
$this->post_id[] = $post_data->id;
$this->section_id[] = $post_data->section_id;
$this->user_id[] = $post_data->user_id;
$this->post_title[] = $post_data->title;
$this->post_details[] = $post_data->details;
$this->post_date[] = $post_data->date;
$this->post_category[] = $post_data->category;
$this->post_display[] = $post_data->display;
}
}
}
Your loop would likely be something like:
for ($m=1; $m<=$num_of_rows; $m++) {
$post_id = $POSTS->post_id[$m];
$section_id = $POSTS->section_id[$m];
$user_id = $POSTS->user_id[$m];
$post_title = $POSTS->post_title[$m];
$post_details = $POSTS->post_details[$m];
$post_date = $POSTS->post_date[$m];
?>
<div id="related_post">
<h4><?php echo $post_title;?></h4>
<p><?php echo $post_details;?></p>
</div>
<?php
}
In my class I should use the following instead of the current one:
$results = $stm->fetchAll(PDO::FETCH_OBJ);
I will not get any advantages of my current class properties.
In my index file I will loop through the $results using foreach loop as the following:
foreach($results as $post){
$post_title = $post->title;
$post_details = $post->details;
}
and so on...
I'm experimenting with PDO and I had the same issue with PDO::FETCH_OBJ
I'm using PHP 5.6 in xampp 5.6.30
needless to say that
- the DB name is animals
- it has three columns only : animal_id, animal_type, animal_name
the following test code works fine and outputs all the records (that in my test DB are only eleven)
$stmt = $dbh->prepare("SELECT * FROM animals");
$stmt->execute();
if($stmt->rowCount() > 0) {
while($obj = $stmt->fetch(PDO::FETCH_OBJ)) {
echo $obj->animal_type . " " . $obj->animal_name . "<br>";
}
}
perhaps you may insert the counters inside the loop or, even better, make the query to properly limit the range.
Anyway, the code above, as expected outputs what follow
kookaburra bruce
emu bruce
goanna bruce
dingo bruce
kangaroo bruce
wallaby bruce
wombat bruce
koala bruce
kiwi cambiato
pippo zollo
pippz zoll2
I am trying to save what will amount to a small list of ids in user meta, but for some reason I am only able to save the most recent visit. Is there something obviously wrong with my approach?
function check_visit() {
$user = get_current_user_id();
$post_visits = get_user_meta($user, 'post_visits', true);
$visited = explode(",",$post_visits);
$id = (string)the_ID();
if($id && !in_array($id, $visited)) {
$visited[] = $id;
update_user_meta($user, 'post_visits', implode(",", $visited));
}
print_r(implode(",",$visited));
}
Actually
$visited[] = $id
is correct!
The issue is that you are using the_ID() function, this function print the ID, do not return any value.
The correct function should be get_the_ID()
Your code should look like this:
function aw_check_visit(){
$user = get_current_user_id();
$post_visits = get_user_meta($user, 'post_visits', true);
$visited = explode(",",$post_visits);
$id = (string)get_the_ID();
if($id && !in_array($id, $visited)) {
$visited[] = $id;
update_user_meta($user, 'post_visits', implode(",", $visited));
}
}
You need to be using array_push instead of adding it to the array like you have.
Change this
$visited[] = $id;
to
array_push($visited, $id);
I have a select query and then another select query but for another table. I need to run the first query, then if it finds something, show a table with a foreach loop. And then, a second query run and select another table with a foreach loop too.
This is my DB class to run my DB :
class DB {
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_count = 0;
public $_results;
private function __construct() {
try {
$this->_pdo = new PDO(...);
} catch(PDOException $e) {
die($e->getMessage());
}
}
public static function getInstance() {
if(!isset(self::$_instance)) {
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = array()) {
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
if(count($params)) {
foreach($params as $param) {
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
Then, on a page I have this following :
<?php if ($st = DB::getInstance()->query("SELECT * FROM resum WHERE form_id = ? ORDER by date DESC", array(Input::get('formID')))) {
if ($st->count()) { ?>
<div id="topSeparateurClient">
<div>Date</div>
<div>Concessionnaire</div>
<div>Client</div>
<div>Voiture</div>
<div>Prix</div>
<div>Statut</div>
</div>
<div style="clear:both;"></div>
<?php
foreach($st->_results as $result) {
echo "<div class=\"clientGenInfos\">
<div><b>".substr($result->date, 0, 10)."</b> / ".substr($result->date, 10)."</div>
<div>".$result->concessionnaire."</div>
<div>".$result->client."</div>
<div>".$result->voiture."</div>
<div>".$result->prix."</div>";
if ($result->statut == 'En Attente') {
echo '<div class="enAttente"><span>En Attente</span></div>';
} else if ($result->statut == 'Accepter') {
echo '<div class="accepter"><span>Accepter</span></div>';
} else if ($result->statut == 'Refuser') {
echo '<div class="refuser"><span>Refuser</span></div>';
}
echo " </div>
";
}
} else {
echo '<div class="aucuneDemande">Nothing from now.</div>';
}
}
?>
Then a second block, almost identical but with another table name in his query. The problem now is that my second table have the same values as the first one..I am stuck here, reading stuff on the net and nothing about this situation. I am still new to PDO object! please help!
EDIT ---
This is my second block..
<?php
if ($st = DB::getInstance()->query("SELECT * FROM users WHERE users.group = 3 ORDER by date DESC")) {
if ($st->count()) { ?>
<div id="topSeparateurClientConc">
<div>Prénom et Nom</div>
<div>Adresse</div>
<div>Nom d'utilisateur</div>
<div>Date d'inscription</div>
<div>Demandes reçues</div>
</div>
<div style="clear:both;"></div>
<?php
foreach($st->_results as $result2) {
echo "<div class=\"clientGenInfosConc\">
<div>".$result2->name."</div>
<div>".$result2->adresse."</div>
<div>".$result2->username."</div>
<div><b>".substr($result2->joined, 0, 10)."</b> / ".substr($result2->joined, 10)."</div>
<div>".$result2->concessionnaire."</div>
</div>";
}
} else {
echo '<div class="aucuneDemande">Aucune demande transférable en ce moment</div>';
}
}
?>
Do not write your own PDO wrapper. Period.
PDO is already a wrapper. Written by the professionals. It has some drawbacks, but at least it has no harmful features which newbie programmers introduce in hundreds.
If you want static method to get instance - all right, have it. But leave the rest for raw PDO. Saving yourself one function call doesn't worth struggling against fallacies of your own wrapper.
Do not save on calls at all! Look what are you doing:
<?php if ($st = DB::getInstance()->query("SELECT * FROM resum WHERE form_id = ? ORDER by date DESC", array(Input::get('formID'))))
It cannot be even read without scrolling. Are you fined for every extra line or what?
This one single line contains almost dozen operators!
This is called "write-only" style.
You are saving yourself a linefeed to write faster, but when it come to reading, you'll run here, crying "read my code for me!".
Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live.
Especially if it's you who have to maintain. Look:
<?php
$sql = "SELECT * FROM resum WHERE form_id = ? ORDER by date DESC";
$st = DB::getInstance()->query($sql, array(Input::get('formID')));
if ($st)
One can read and comprehend it. And noone died for splitting this call in four lines. Now add a couple:
$sql = "SELECT * FROM resum WHERE form_id = ? ORDER by date DESC";
$st = DB::getInstance()->prepare($sql);
$st->execute(array(Input::get('formID')));
$data = $st->fetchAll();
if ($data)
assuming getInstance() returns raw PDO instance. And your code will be perfectly fine working.
All right, I can understand a programmer's desire to avoid repetitions. Here is a solution that solves this problem without drawbacks:
$sql = "SELECT * FROM resum WHERE form_id = ? ORDER by date DESC";
$data = DB::prepare($sql)->execute(array(Input::get('formID')))->fetchAll();
And quit that idea of writing SQL calls right in the template. Fetch all your data first and then include a file with markup.
<?php if ($data): ?>
<div id="topSeparateurClientConc">
<div>Prénom et Nom</div>
<div>Adresse</div>
<div>Nom d'utilisateur</div>
<div>Date d'inscription</div>
<div>Demandes reçues</div>
</div>
<div style="clear:both;"></div>
<?php foreach($data as $result2): ?>
<div class="clientGenInfosConc">
In codeigniter 1.73 i'm trying to display books by category. so if i have a category called cars, i should see a list of books within cars. so i tried a nested foreach loop to accomplish this but can't seem to get it to work.
<?php
class Book_model extends Model {
function books_by_category()
{
$this->db->select('*');
$this->db->from('categories');
$this->db->join('books', 'books.category_id = categories.id');
$query = $this->db->get();
return $query->result();
}
}
then in the view:
foreach($data as $category) {
if (sizeof($category['books']))
{
foreach($category['books'] as $book)
{
<li>$book->book_number anchor("book/chapters/$book->id", $book->book_title)</li>
}
} else {
// show 'no books'
}
}
controller:
function index() {
$data = array();
if($query = $this->book_model->books_by_category())
{
$data['books_by_category'] = $query;
foreach($query as $row)
{
if (!isset($data[$row['id']]))
{
$data[$row['id']] = $row;
$data[$row['id']]['books'] = array();
}
$data[$row['id']]['books'][] = $row;
}
$data['main_content'] = 'books_view';
$this->load->view('includes/template', $data);
}
}
Foreach does not have an "else" clause, as you've used.
foreach($category['books'] as $book)
{
// show books
} else {
// show 'no books'
}
Instead, you could do this: (my PHP is rusty)
if(count($category['books']) <= 0)
{
//No books
}
else
{
foreach($category['books'] as $book)
{
//You have books
}
}
A couple of points
function books_by_category()
{
$this->db->select('*');
$this->db->from('categories');
$this->db->join('books', 'books.category_id = categories.id');
$query = $this->db->get();
return $query->result();
}
This code returns all columns for categories and books that have a category set, is this really what you are trying to do? The function name 'books_by_category' would suggest to me that you are only interested in books for one specific category, from looking at your question I'm guessing this isn't the case.
Presuming you are trying to get all books but group them by category I would do the following:
model
function get_books()
{
$this->db->select('*');
$this->db->from('books');
$this->db->join('categories', 'categories.id = books.category_id');
$query = $this->db->get();
if($query->num_rows() == 0)
{
#no books
return false;
}
return $query->result();
}
controller
function index() {
$data = array();
$book_list = $this->book_model->get_books();
if($book_list)
{
$categories = array();
$books_by_category = array();
foreach($book_list as $book)
{
$category_id = $book['category.id'];
$category_name = $book['category.name'];
if(array_key_exists($category_id, $categories))
{
$categories[$category_id] = $category_name;
}
if(array_key_exists($category_id, $books_by_category))
{
$books_by_category[$category_id] = array();
}
$books_by_category[$category_id][] = $book;
}
$data['categories'] = $categories;
$data['books_by_category'] = $books_by_category;
}
$data['main_content'] = 'books_view';
$this->load->view('includes/template', $data);
}
and the view
<?php if(isSet($books_by_category)) : ?>
<?php foreach($books_by_category as $category => $book_list): ?>
<p>Category: <?php echo $categories[$category]; ?></p>
<ul>
<?php foreach($book_list as $book) : ?>
<li><?php echo $book->book_number; ?>. <?php echo anchor('bible/chapters/' . $book->id, $book->book_title); ?></li>
<?php endforeach; ?>
</ul>
<?php endforeach; ?>
<?php else: ?>
<p>Sorry dude, no books.</p>
<?php endif; ?>
There are a few errors in the code which might be causing this.
You have an extra closing bracket before the end of the foreach loop in your controller.
In your view, you are looping through the books category as $book but then you are trying to work with the $row object inside the loop. Try changing this to $book.
Also in your view, you trying to output some HTML without closing out of your PHP tags. The <li> tags in your code are inside your PHP block and then you try to open up a new PHP block again without ever closing the first one.
I came across this and tried to follow along with the example #mattumotu posted and it was really helpful, but I think it might have some errors - specifically with the way the array is being indexed and then looped through. If you are using a number as an id value, and your ids do not start from zero and increase in numerical order from 0 to x, then you will get unknown index orders in your view when you attempt to loop through the array (at least I did). So I modified the example as follows (note I changed the variable names slightly for my own use):
Model:
public function get_imagery_by_category(){
$this->db->select('extra_imagery.*', FALSE); //MH - not sure what FALSE does here
$this->db->select('extra_image_categories.id as cat_id, extra_image_categories.name as cat_name', FALSE); //MH alias the category id and name as they are the same column names as the imagery name and id
$this->db->from('extra_imagery');
$this->db->join('extra_image_categories', 'extra_image_categories.id = extra_imagery.cat'); //get all images where the image cat matches category id
$this->db->order_by('extra_image_categories.id');
$query = $this->db->get();
if($query->num_rows() == 0){
return false;
} else {
return $query->result_array();
}
}
Here we're just sorting all of our items by the category ID, to ensure we are moving through all of our items in numerical order by their category ID, essentially listing items out by category.
Controller:
$imagery_list = $this->imagery_model->get_imagery_by_category();
if($imagery_list){
$categories = array();
$imagery_by_category = array();
$curCatIndex = -1;
$curCatID = NULL;
foreach($imagery_list as $i=>$image){
$category_id = $image['cat_id'];
$category_name = $image['cat_name'];
if ($curCatID != $category_id){
$curCatIndex+=1;
$categories[$curCatIndex] = $category_name;
$curCatID = $category_id;
}
$imagery_by_category[$curCatIndex][] = $image;
}
//print_r($imagery_by_category);
$data['categories'] = $categories;
$data['imagery_by_category'] = $imagery_by_category;
}
Here we're setting an array to hold our categoriesand an array to hold our items. The $imagery_by_category will be a multidimensional array, such that all items in the first category end up in the first array, all items in the second category are in the second array, etc. Like this:
$imagery_by_category[0][0] = category0, item0
$imagery_by_category[0][1] = category0, item1
$imagery_by_category[1][0] = category1, item0
We're setting a counter ($curCatIndex) that will keep track of each time we hit a new category id, and a variable for the category ID to check if our category id has changed ($curCatID). If we hit a new category ID, we know we've collected all the items for that category, so we increment the curCatIndex counter:
$curCatIndex+=1;
Because our $curCatID starts out as NULL when we begin our loop, we increment the $curCatIndex so that our array will start out at index 0.
Whenever we hit a new category id, we push the name of that category to our $categories array:
$categories[$curCatIndex] = $category_name;
and set the $curCatID equal to our new id:
$curCatID = $category_id;
Then, regardless of whether we are in a new category or not, we push the item to the proper place in the multidimensional array:
$imagery_by_category[$curCatIndex][] = $image;
and lastly we just make these arrays available to our view:
$data['categories'] = $categories;
$data['imagery_by_category'] = $imagery_by_category;
Then, in our view:
<?php if(isSet($imagery_by_category)) : ?>
<?php foreach($categories as $i=>$category_item): ?>
<p><?php echo $category_item ?></p>
<?php foreach($imagery_by_category[$i] as $image_item) : ?>
<?php
echo $image_item['id'];
?>
<?php endforeach; ?>
<?php endforeach; ?>
<?php else: ?>
<p>No imagery</p>
<?php endif; ?>
We have a nested loop. The outer loop loops through our categories:
<?php foreach($categories as $i=>$category_item): ?>
Notice that we've added a variable $i to keep track of the loop index (i.e. array index)
Then we print out the name of the category:
<p><?php echo $category_item ?></p>
and then the inner loop loops through the items in that category:
<?php foreach($imagery_by_category[$i] as $image_item) : ?>
Notice we're using the $i variable here to make sure we select the right dimension from our item array.
Then inside this loop you can do whatever you want. Here I'm just printing out the unique id of my item:
echo $image_item['id'];
Probably a more elegant way to do this, but hope it helps someone. I banged my head against the wall on this for awhile. Thanks to mattumotu for getting me on the right track. I've posted a clearer code example here:
http://mikeheavers.com/main/code-item/order_items_in_one_database_table_by_categories_from_another_database_table
I'm trying to display all the values from a specific column created by my Wordpress plugin (specifically, the ID's). Here is the code I have managed to use to display the column names, but I cannot get it to just display all the ID's. Here is the code:
function test() {
global $wpdb;
global $table_name;
$testing = $wpdb->get_col_info('name', 0);
foreach ($testing as $test) {
echo $test;
}
}
And here you can see the output:
www.matthewruddy.com/premiumslider
Can anyone help me out?
It seems you want data instead of column information. So you need to another function.
$testing = $wpdb->get_results("SELECT id FROM mytable")
foreach ($testing as $test) {
echo $test->id
}
EDIT:
OK, how about this one:
$wpdb->show_errors();
echo 'Listing from table: $table_name<br>';
$ids = $wpdb->get_col($wpdb->prepare("SELECT id FROM %s", $table_name));
if ($ids) {
echo 'printing results:<br>';
foreach($ids as $id) {
echo $id;
}
} else {
echo 'no results or error<br>';
echo 'error: ' . $wpdb->print_error();
}
$wpdb->hide_errors();
If this doesn't help you either to get your ID's or to figure out what the error is, I am lost.
Might be a little late for this question, but I think it is still relevant to todays WordPress world and also a situation I ran into creating my own plugin.
So for anyone else, this worked for me. The OP almost had it. However, $wpdb->get_col_info() relies on a cache result for its results so a $wpdb->get_results or get_row or query needed to be called first. :)
I also liked littlegreen's error handling.
function test() {
global $wpdb, $table_name;
$wpdb->show_errors();
$return = 'Listing from table: '.$table_name.'';
$results = $wpdb->get_results("SELECT * FROM ".$table_name);
$nameCols = $wpdb->get_col_info('name');
if (is_array($nameCols)) {
$return .= 'printing results:';
foreach($nameCols as $name) {
$return .= ' '.$name;
}
} else {
$return .= 'no results or error'.
'error: ' . $wpdb->print_error();
}
$wpdb->hide_errors();
}