2

How to make the array of id that we call from a table?

What I want is like this :

$array = array(1, 2, 3, 4, 5); // **1 - 5 select from a table**.

Thank you

Code :

$query = mysqli_query($conn, "SELECT * FROM tableA");
while($row = mysqli_fetch_assoc($query )){          
    $a = implode(',',(array)$row['id_add_user']);
    echo $a;
}

What I get from echo $a is 12345 not 1,2,3,4,5

3
  • you mean range : eval.in/1002578 Commented May 11, 2018 at 7:19
  • 1
    Have you got any code which selects the data from the table, there are a variety of ways to convert it to what you want depending on how you fetch the data. Commented May 11, 2018 at 7:21
  • I have edit my question, please take a look Commented May 11, 2018 at 7:34

4 Answers 4

2

Add all the elements to an array, then implode() it into one string with your desired deliminator (here, its ", ") once all results are fetched.

$result = [];
$query = mysqli_query($conn, "SELECT * FROM tableA");
while($row = mysqli_fetch_assoc($query)){          
    $result[] = $row['id_add_user']);
}

echo implode(", ", $result);
Sign up to request clarification or add additional context in comments.

1 Comment

You are the best ! Thank you !
1

Collect necessary values into an array.

$a = [];
while(...){          
    $a[] = $row['id_add_user'];
}
echo implode(',', $a);

Comments

1

You are trying to implode() the values for each row, you need to build an array of all the values and then output the result imploded. Also if you just want one column - just fetch that column in your SQL

You can further simplify it to...

$query = mysqli_query($conn, "SELECT id_add_user FROM tableA");
$rows = mysqli_fetch_all($query );
echo implode(',',array_column($rows, 'id_add_user' ));

mysqli_fetch_all allows you to fetch all the data in one go. Then use array_column() to extract the data.

Comments

-1
$array = array(1,2,3,4,5);

Use below SQL query for selecting the array id data

SELECT column_name(s)
FROM table_name
WHERE column_name IN $array;

2 Comments

what I want is number 1,2,3,4,5 in array is come from coloumn id on tableA
This would result in ...WHERE column_name IN Array ( ), and won't work. Try printing an array as a string and you'll see. :)

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.