0

How can i create an array from the result? I would like to use the array in a mysql IN() query.

//$array = array();
        $get_subscategoria = mysqli_query($kapcs, "SELECT kat_id FROM termek_kategoria WHERE kat_parent = '$id'");
        if(mysqli_num_rows($get_subscategoria) > 0 )
        {
            while($sub_kat = mysqli_fetch_array($get_subscategoria))
            {
                echo $sub_kat['kat_id'];
                //$array[] = $sub_kat;
            }
        }
        //print_r( $array );

Now, this code gives back 4 row ID, that works okay. I would like an array with these ID-s, like 1,2,3,4.

3
  • use prepared statements Commented Feb 24, 2017 at 8:55
  • do you need an array or a string? Commented Feb 24, 2017 at 8:59
  • I want to use it in a mysqli query, with an IN() function. Commented Feb 24, 2017 at 9:04

3 Answers 3

2

Instead of:

while($sub_kat = mysqli_fetch_array($get_subscategoria))
{
    echo $sub_kat['kat_id'];
    //$array[] = $sub_kat;
}

use:

$array = mysqli_fetch_assoc($get_subscategoria);
Sign up to request clarification or add additional context in comments.

Comments

1
while($sub_kat = mysqli_fetch_array($get_subscategoria))
{
$array[] = $sub_kat['kat_id'];
}
echo implode(",",$array);

it give a result like 1,2,3,4

Comments

1

For MySQL, also you can use group_concat, only gives you one record:

SELECT GROUP_CONCAT(kat_id) AS kat_id
FROM termek_kategoria 
WHERE kat_parent = '$id'
GROUP BY kat_parent

2 Comments

It gives Undefined index: kat_id error. But the name in the table is kat_id, thats correct.
@Dave599 Then use kat_id as alias, check it again.

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.