Search code examples
phpmysqlcsvmysqlifputcsv

How to add an entry to mysqli array


I am trying to add a single column at the beginning of a csv file using the code below:

while ($row = mysqli_fetch_array($rows, MYSQL_ASSOC)) {
    $list = "'2795', $row";
    fputcsv($output, $list);
}

What am I missing? I know it's something simple. Thank you in advance.


Solution

  • You can't just join those values together:

    $list = "'2795', $row";
    

    Since $row returns a row result array, treat it as such, push that value inside:

    $output = fopen('whatevername.csv', 'a+');
    while ($row = mysqli_fetch_array($rows, MYSQLI_ASSOC)) {
        $row[] = '2795'; // `$row` is an associative array
        fputcsv($output, $row);
    }
    fclose($output);
    

    Sidenote: This is a truncated code, so just make sure you have that file handle above this code that you presented.