Search code examples
phploopsimplode

Implode ids within a while loop and add commas between


I'm trying to display some sub-content so I need to get the child id's of their parent.

This is how I wanted to do it:

$ids        = "SELECT * FROM `web_categories` WHERE parent_id = 14 AND published = 1";
$idscon     = $conn->query($ids);
while ($ids = $idscon->fetch_array()){
    $idss .= $ids['id'];
}

$project1       = "SELECT * FROM `web_content` WHERE catid in ('$idss') AND state = 1";
$projectcon1    = $conn->query($project1);
$projectcr1     = array();
while ($projectcr1[] = $projectcon1->fetch_array());

I tried imploding $idss like this:

$implode = implode(',', $idss);

But this gives me Invalid arguments passed. What am I doing wrong?


Solution

  • You are doing wrong in the first while loop.

    Here it is, $idss .= $ids['id'];, You are doing wrong this. You are storing value in a variable as string, but when you try to implode this... It throws an error!!! Cause implode() use to make array into string. So follow the below steps.

    Change $idss .= $ids['id']; to $idss[] = $ids['id']; and instead of implode() use the join().

    Create an array names $idss, and push or insert the ids into that array. Then implode/join that IDs.

    $idss = array();
    while ($ids = $idscon->fetch_array()){
        $idss[] = $ids['id'];
    }
    $implode = implode(',', $idss);
    

    Now you can use this $implode variable in the next query.