Trying to export MySQL query as CSV using PHP - php

I'm getting a warning
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, array
given
when trying to export a MySQL query result as CSV using PHP code like this:
public static function exportLocationCSV($id){
$sql =<<<EOF
SELECT col1, col2, col3
FROM table1
JOIN table2 ON table1.col0=table2.col0
WHERE table1.col0 = $id;
EOF;
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));
$query_export= self::$db_connection->query($sql);
$rows = array();
while($r = mysqli_fetch_assoc($query_export)){
$rows[] = $r;
}
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
}

You're mixing mysql_* and mysqli_* API's. mysql_fetch_assoc() will not work with the mysqli_ API. Your second while loop is the one using the wrong function call.
This line:
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
should be change to the correct function call:
// loop over the rows, outputting them
foreach($rows AS $row) fputcsv($output, $row);

mysql_fetch_assoc used to fetch a result row as an associative array here is more about mysql_fetch_assoc
what you are trying to do is to pass $rows which is array while mysql_fetch_assoc expecting you to pass mysql_query

Related

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);
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).
When you initially create the $list array, it is an array containing one array. But when you add more values to it from your query results, you are pushing strings onto the end of it, not arrays. In effect, you will be making something like
$list = array (
array('old_campaign_name', 'new_campaign_name'),
'first campaign',
'second campaign',
'etc.',
...
);
Because of this, when you loop over $list, the first value should work with fputcsv, because it is an array, but any subsequent values will be strings instead of arrays and will cause the error you are seeing.
You should be able to fill the $list like this:
while ($row = $query->fetch_assoc()) {
$list[] = $row;
}
$list[] = $row will not overwrite the values previously in $list. From the PHP documentation for array_push:
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
It works like this :
while ($row = $query->fetch_assoc())
{
// array_push($list,$row['campaign'],'');
array_push($list,array($row['campaign'], ''));
}

Outputting Column titles in CSV Export

I have this query that exports to a csv file. It works fine the only thing i can't figure out is i need to export the column titles as well, and have them display as Full Name, UserName, Flag and Reason. Below is the code and it exports all the rows fine but I'm not sure how to export the column titles above the respected rows.
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=blackflag_bidders.csv");
header("Pragma: no-cache");
header("Expires: 0");
//SQL Query for Data
$sql = "SELECT ui.first_name, ui.last_name, u.username,
if(u.flag=1,'BLK', if(u.flag=2,'NAA','')) flag,
if(u.flag!=0, IFNULL(ui.note,''),'') reason
FROM user u
LEFT JOIN user_info ui ON ui.user_id=u.id
WHERE u.flag!=0;";
//Prepare Query, Bind Parameters, Excute Query
$STH = $sam_db->prepare($sql);
$STH->execute();
//Export to .CSV
$fp = fopen('php://output', 'w');
//fputcsv($fp);
while ($row = $STH->fetch(PDO::FETCH_NUM)) fputcsv($fp,$row);
fclose($fp);
One way would be to fetch the first result by associative, those associative indices are columns anyway. Apply array_keys to get those, then first add the headers, then the first fetched row, then loop the rest.
// first set
$first_row = $STH->fetch(PDO::FETCH_ASSOC);
$headers = array_keys($first_row);
// $headers = array_map('ucfirst', $headers); // optional, capitalize first letter of headers
fputcsv($fp, $headers); // put the headers
fputcsv($fp, array_values($first_row)); // put the first row
while ($row = $STH->fetch(PDO::FETCH_NUM)) {
fputcsv($fp,$row); // push the rest
}
fclose($fp);
The answer to this will depend upon whether you already know the column names or not. It seems like you do (e.g. you are already calling 'Select ui.firstname...')
If you do not, you can get the names by looking at this thread:
What is the Select statement to return the column names in a table
Once you have the names, you simply need to create a single row with the names and add them to file by modifying your code as:
//Export to .CSV
$columnNamesRow = "FirstName, LastName, UserName";
$fp = fopen('php://output', 'w');
fputcsv($fp, $columnNamesRow);
//fputcsv($fp);
while ($row = $STH->fetch(PDO::FETCH_NUM)) fputcsv($fp,$row);
fclose($fp);
You can get a column in CSV by simply displaying your results in Tabular form here in the page using <table> tag of HTML.
$result = "<table>";
while ($row = $STH->fetch(PDO::FETCH_NUM)){
$result .= "<tr><td>$row1</td><td>$row2</td><td>$row3</td></tr>";
}
$result .= "</table>";
fputcsv($fp, $result);
By $row1, $row2, I mean the values you get in your resultset

creating a CSV file from MySQL Table data in PHP

I have this code in PHP:
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=calls.csv');
// create a file pointer connected to the output stream
$output = fopen($_SERVER["DOCUMENT_ROOT"].'/file_dump/price_tariffs/calls.csv', 'w');
// output the column headings
fputcsv($output, array('Column 1', 'Column 2'));
// loop over the rows, outputting them
$sql="SELECT * from call_costs where sequence < '50' ";
$rs=mysql_query($sql,$conn);
while($result = mysql_fetch_array($rs)) {
fputcsv($output, $result["number"]);
}
its creating the file name calls.csv in the price_tariffs directory but its only adding the column 1 and column 2 and not the data from the while loop
i have check the loop and echoed data inside the loop which displays fine
fputcsv takes the second parameter as an array(), "and you already used fputcsv outside of the loop passing the second param as an array"[*] with two values inside.
Try to do the same inside your loop:
fputcsv($output, array($result["number"], $result["somethingelse"]));
[*]: edited, added enquoted sentence after clarifying in the comments below.
Select only the columns that you want:
$sql = "SELECT column1, column2 FROM call_costs WHERE sequence < '50'";
Then use mysql_fetch_assoc() to fetch each row as an associative array, and output that:
$rs=mysql_query($sql,$conn);
while($row = mysql_fetch_assoc($rs)) {
fputcsv($output, $row);
}
fputcsv()'s second argument is supposed to be an array of the values that should be put into fields in the CSV file.
since you're sending the data to the client directly, you should echo it instead of saving it to a file :) Open the php://output instead:
Try this (from powtacs answer:
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=calls.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Column 1', 'Column 2'));
// loop over the rows, outputting them
$sql="SELECT * from call_costs where sequence < '50' ";
$rs=mysql_query($sql,$conn);
while($result = mysql_fetch_assoc($rs)) {
fputcsv($output, $result);
}
Also please note that mysql is depreciated, and you should use mysqli or PDO instead
Checkout the mysql_fetch_array in the php manual, so, we can say:
...
while($result = mysql_fetch_array($rs,MYSQL_NUM)) {
fputcsv($output, $result);
}
Just add the second optional parameter MYSQL_NUM to return numerical array and supply all of it as a parameter in fputcsv. By this way you will get all the raw's fields data in your csv file.

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.
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.

Exporting data from database to csv file using php

I am able to export database to csv but my code somehow imports twice the data to my csv file. I.e same column twice side by side.this is my code. I think my problem is with the implode statment. Any help would be appreciated.
<?php
$db = new sqlite3('I:\preethi\webbs.db');
$headers = array
('Id','CompanyId','DateTime','Serial','DeviceId','AgentAId','GpsAddress','Targa','CommonRoadDescription'
,'RoadCivicNumber','VehicleBrandDescription','VehicleModelDescription' ,'VerbaliVehicleTypeDescription','CommonColorVehicleDescription','VerbaliRuleOneCode','VerbaliRuleOneDes
cription','VerbaliRuleOnePoints'
,'VerbaliClosedNoteDescription','Points','VerbaliMissedNotificationDescription
','MissedNotificationNote','StatementNote');
$results = $db->query('select'.implode (',',$headers).'from VerbaliData');
//$results = $db->query( 'select
Id ,CompanyId ,DateTime ,Serial ,DeviceId ,AgentAId
,GpsAddress ,Targa ,CommonRoadDescription ,RoadCivicNumber ,VehicleBrandDescription
,VehicleModelDescription ,VerbaliVehicleTypeDescription ,CommonColorVehicleDescription
,VerbaliRuleOneCode ,VerbaliRuleOneDescription ,VerbaliRuleOnePoints ,VerbaliClosedNoteDescription
,Points ,VerbaliMissedNotificationDescription ,MissedNotificationNote ,StatementNote from
VerbaliData');
$fp = fopen('explores.csv', 'w');
fputcsv($fp,$headers);
while ($row = $results->fetchArray()) {
fputcsv($fp, $row);
}
fclose($fp);
?>
Just try with :
while($row = $results->fetchArray(SQLITE3_NUM)) {
Or
while($row = $results->fetchArray(SQLITE3_ASSOC)) {
More Details: http://php.net/manual/en/sqlite3result.fetcharray.php
You have a slight prob in your code fetchArray() returns two array sets one associative and one is numbered, use fetchArray(SQLITE3_NUM) or fetchArray(SQLITE3_ASSOC).

Categories