0

My goal: insert into a variable an array of items coming from a query and then print it

steps:

  1. launch the query
  2. do something with php
  3. print the variable $report = 'this is your list: $list';

tried this:


    $myquery = mysqli_query($dbconnection, "SELECT ...");

    while($row = mysqli_fetch_assoc($myquery)) {
      $my_array = $row['field'];
      echo "$my_array, "; /* here I've the full list*/
    }

    $report = 'this is your list:' .$my_array. '.';

    echo "$report"; /*I've only one item and not all the list*/

isabella
  • 3
  • 3
  • All basic questions are already answered several times. Please enjoy the wealth of pre-existing knowledge by searching Stackoverflow before posting a new question. – mickmackusa Jun 10 '20 at 09:34
  • 1
    Thanks. i reached my goal not using php but simply adding a "GROUP_CONCAT" in mysql query – isabella Jun 10 '20 at 10:18

2 Answers2

0

Your first echo is called several times because it is in the loop. In every iteration you are replacing your content of $my_array.

Instead, try to attach it:

$my_array[] = $row['field'];

For more information see https://www.php.net/manual/de/language.types.array.php

ya-cha
  • 602
  • 2
  • 6
  • 14
0

This is normal. Your while loop doing a "step" for each row found with your query. You assigned $my_array as the "column" with the name field.

So at the end of the while loop, you'll get only the last column field of the last row.

Instead, try this

$myquery = mysqli_query($dbconnection, "SELECT ...");
$myWholeList = ''; // HERE

while($row = mysqli_fetch_assoc($myquery)) {
    $my_array = $row['field'];
    echo "$my_array, ";
    $myWholeList .= '$my_array '; // HERE
}

$report = 'this is your list:' .$my_array. '.';
echo "$myWholeList"; // HERE

I've done a string concatenation, but you can do it with array and print_r() function. Have a look on this thread to see how to append data to an array.

mysqli_fetch_array while loop columns

EDIT: Based on @isabella 's comment, she wants to display 7 items of array.

Two way :

  • Use print_r() or var_dump() which is the best to display an array (without taking care about rendering)

  • Add to $myWholeList variable each item.

e.g.

$myquery = mysqli_query($dbconnection, "SELECT ...");
$myWholeList = ''; // HERE

while($row = mysqli_fetch_assoc($myquery)) {
    $my_array = $row['field'];
    echo "$my_array, ";

    // HERE
    foreach($row as $field) {
        $myWholeList .= $field . ' ';
    }
    $myWholeList .= '<br>'; // NEW LINE
}

$report = 'this is your list:' .$my_array. '.';
echo "$myWholeList"; // HERE
D. Schreier
  • 1,700
  • 1
  • 22
  • 34
  • thanks for your reply: I tried it but when I print the $myWholeList variable it prints 7 times the string $my_array instead of printing the 7 items of the array... – isabella Jun 10 '20 at 10:11
  • @isabella I just add some explanation about your request ;) – D. Schreier Jun 10 '20 at 10:29