Rookie Recruits
Rookie Recruits

Reputation: 93

Array to string conversion error on While and foreach statement

I have been looking for answers on stack and they do have a few examples on this but for some reason the only way I can get this to display the categories is by using the foreach statement. Doesn't seem like any one else I have read on needs this but I cannot get the DB category list to display unless the foreach statement is included.

What I am trying to do, is to pull all of the current categories in the active item listing but I only need one of each listing. If there are 100 small_cents in the inventory list I only need it to show me the category once but I also need one of all the categories that currently have active items in the inventory in order to use in a later script to show a report of total price value of items in each category.

At the moment I have it showing me the full list of categories for every category that has active items in the inventory. The problem is that it is showing me the same category more than once, as many time as there are items in the inventory for that category. Please view the code below. I appreciate any help.

    function categories($dbCon){
        if($res = $this->dbConnection->query("SELECT categoryName FROM Table")){
            $categoryName = array();
                while($data = $res->fetch_assoc()){
                    $categoryName[] = $data['categoryName'];
                }
                foreach($categoryName as $categoryName){
                    echo $categoryName."\n";
                }
        }
    }

Instead this is what I am getting:

Small_Cents Small_Cents Small_Cents Small_Cents CVC_Top_Picks Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents Small_Cents

I only need:

Small_Cents

CVC_Top_Picks

If I add LIMIT 1 in the sql query I only get Small_Cents.

On the front end all I have is this

include('class/reports-class.php');
$reportsClass = new reportsClass($dbCon);

And

<?php $reportsClass->categories($dbCon); ?>

Upvotes: 0

Views: 341

Answers (1)

CodeBoy
CodeBoy

Reputation: 3300

Use ...

SELECT DISTINCT categoryName FROM Table

Upvotes: 1

Related Questions