简体   繁体   中英

fetching one column values from multiple rows and Add comma in echo/print_r in php

I am trying to fetch multiple rows and want to show only one respective column values from each fetched row (while separated by commas or space between them).

I tried a number of approaches (commented code) but nothing happened.

$query="SELECT tests FROM p_tests WHERE app_id='$id' ";
        //SELECT STRING_AGG(TaskName, ', ') 
        // FROM Tasks;
    $run=mysqli_query($db,$query);
    while ($run=mysqli_fetch_array($res)) {
      // $tname=$run['tests']; 
      // echo $tname;

      // $Var=implode(', ',$run['tests']);
      // echo $Var;


        // $run = implode(', ', array_column($run,0));
        // echo $run;

        //$test = array_column($run, 'tests');
        // print_r($run);
        // echo $run;
}
?>

If $run['tests'] is the specific column that you want to fetch from each row, then use the code as below:

$query="SELECT tests FROM p_tests WHERE app_id='$id' ";
        //SELECT STRING_AGG(TaskName, ', ') 
        // FROM Tasks;
    $run=mysqli_query($db,$query);
    $arr = [];
    while ($run=mysqli_fetch_array($res)) {
          $tname=$run['tests'];
          $arr[] = $tname; 
    }
    $new_arr_comma = implode(',',$arr); // For comma seperated;
    $new_arr_space = implode(' ',$arr); // For space seperated;

    print_r($new_arr_comma);
    print_r($new_arr_space);
?>

Something like....

<?php

$link = mysqli_connect ( 'localhost', 'user', 'pass', 'db' );

if ( $result = mysqli_query ( $link, "SELECT tests FROM p_tests WHERE app_id = '" . $id . "';", MYSQLI_USE_RESULT ) )
{
    $data = array ( );

    while ( $row = mysqli_fetch_assoc ( $result ) )
    {
        $data[] = $row['tests'];
    }

    mysqli_free_result ( $result );

    echo implode ( ', ', $data );
}

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM