Bifter
Bifter

Reputation:

Wrong output for SQL database query

I have the following:

<?php
$result = mysql_query("SELECT `category_id` FROM `categories` WHERE `category_parent_id` = '80'");
while ($row = mysql_fetch_array($result)){
$childrows [] = $row['category_id'];
$clean = array_unique($childrows);
$category_string = implode(",",$clean);
echo $category_string;
?>

And this outputs:

4747,4847,48,6347,48,63,6447,48,63,64,6847,48,63,64,68,69

I cannot work out why I have the duplicates and some have the comma's missing.

Please help!

Upvotes: 0

Views: 104

Answers (2)

Quassnoi
Quassnoi

Reputation: 425613

Your code won't compile since you didn't close the curly bracket, but it actually outputs this:

47
47,48
47,48,63
47,48,63,64
47,48,63,64,68
47,48,63,64,68,69

without newlines.

Use this:

<?php
$result = mysql_query("SELECT DISTINCT `category_id` FROM `categories` WHERE `category_parent_id` = '80'");
while ($row = mysql_fetch_array($result))
    $childrows [] = $row['category_id'];
echo implode(",",$childrows) . "\n";
?>

Upvotes: 2

Greg
Greg

Reputation: 321766

You're echoing each time around the loop, and don't have linebreaks.

If you had linebreaks it would look like this:

47
47,48
47,48,63
47,48,63,64
47,48,63,64,68
47,48,63,64,68,69

Make a little more sense now?

Upvotes: 4

Related Questions