Search code examples
phpsqlfputcsvarray-push

Array push rows from SQL query


I am trying to save the rows (results) from an SQL query to a csv file. I am using array push in order to put the results in a list. Later I put the data from this list to my csv file.

My code :

    while ($row = $query->fetch_assoc()) 
{
    echo sprintf( $row['campaign']);
    array_push($list, $row['campaign']);

}

The results are there because sprintf works. The problem is with the syntax of array_push. I even tried :

array_push($list, array(''.$row['campaign']);

I am getting an error:

fputcsv() expects parameter 2 to be array

The full code is here :

    $list = array 
    (
        array('old_campaign_name', 'new_campaign_name') 
    );

// table 1
$sql = ('select distinct(campaign) as campaign from '.$table1.'');

// Run the query
$query = $Db->query($sql);

// Check for SQL errors
if ($Db->error) 
{
    return ($Db->error);
}

// Put data in the list

while ($row = $query->fetch_assoc()) 
{
    echo sprintf( $row['campaign']);
    array_push($list,$row['campaign'],'');

}

$fp = fopen($location, 'w');

foreach ($list as $fields) 
{
    fputcsv($fp, $fields);
}

fclose($fp);

Solution

  • As the error says, fputcsv expects each row that you put to be an array, so it can write it out with commas separating the elements. $list should be a 2-dimensional array, so you need to push an array onto it when you're building it.

    while ($row = $query->fetch_assoc() {
        $list[] = array($row['campaign']);
    }
    

    BTW, $list[] = x is equivalent to array_push($list, x).