0

Working on a e-shop, i must read from the DB the products that have productpack not null.

productpack from the DB looks like this : 0141,3122,0104,0111,3114,0106,0117 .

I'm trying to get all the DB items that have productpack set (not null), and make them into an array with arrays with those codes (0141,3122,0104,0111,3114,0106,0117).

function p_productpacks(){

    $productpacks = array();
    $pack = array();

    $q = mysql_query('SELECT productpack FROM products WHERE productpack <> "";');

    while($p = mysql_fetch_object($q)){

        $pack = explode(",", $p);

        $productpacks[] = $pack;

    }

    return $productpacks;

}   
1
  • 3
    This looks like your database model isn't properly normalized. Whenever you feel the need to write your own little micro-database logic inside a database, something is off. Commented Oct 3, 2011 at 10:35

3 Answers 3

1

You need to create an array otherwise, you're overwriting existing packs:

$pack = explode(",", $p->productpack);

$productpacks[] = $pack;

For more information read about array_pushDocs and PHP Arrays Docs (and mysql_fetch_objectDocs).

Sign up to request clarification or add additional context in comments.

3 Comments

So what's your question then?
well ... somehow it doesn't work, i don't know why. the array is empty
well, it will not work as expected if comma is a valid character for a product pack name
0

You can get all productpacks in a CSV array using:

$result = mysql_query("SELECT GROUP_CONCAT(productpack) as productpacks
                       FROM products WHERE productpack <> '' ");
if ($result) {
  $row = mysql_fetch_row($result);
  $productpacks_as_CSV_string = $row['productpacks'];
}

That way you only need to get one row out of the database, saving lots of time.

See: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

Comments

0

mysql_fetch_object returns an object and can't be used with string processing.. if you definitely want to use this, you need to do something like:

$pack=explode(',',$p->productpack);
$productpacks[]=$pack

Or, to use a good old array instead:

while ($p = mysql_query($q))
{
    $pack = explode(",", $p['productpack']);
    $productpacks[] = $pack;
}

1 Comment

hmmm .. this seemsmore close to what i want to do... i will test this now .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.