Hey what I am trying is populate csv with the values from my array. How can I do that ?
$sql = "SELECT accountNumber, Name,studentManager,contract,
nationality,university,major,Course,specialNotes,
Phone,email,birthday,uniAddress
FROM " . $dbname . "
WHERE id ='$id'";
$query2 = mysqli_query($conn, $sql);
$thisArray = mysqli_fetch_all($query2, MYSQLI_NUM);
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=userData.csv");
$fp = fopen('php://output', 'w');
foreach ($thisArray[0] as $row3) {
fputcsv($fp,$row3);
}
fclose($fp);
When you retrieve the data into $thisArray, it creates an array where each row is an array of all the field values. So when you use $thisArray[0] in the following line...
foreach ($thisArray[0] as $row3) {
This just picks up the first row of the data you've retrieved. $row3 will be each individual field and fputcsv is expecting it to be an array.
Just change that line to
foreach ($thisArray as $row3) {
and $row3 will be each row of data.
(Just so there is an answer for this)
Related
Im currently trying to do a loop where it will display all the records in the table. but the result that i get now is it display one data which the last record from the table. what should i do if i want to make it display all the records in table and not only one data being display
$myFile = "testFile.txt";
$fo = fopen($myFile, 'w' ) or die ("cant open file");
$header = str_pad($rekod,0).str_pad($organisasi,5).str_pad($jabatan,40).str_pad($tarikh_kredit,8).str_pad($sec_code,16,"0").str_pad($filler,150)."\n";
$sql = "SELECT * FROM pengerusi_johor WHERE negeri='$negeri'";
$result = mysqli_query($db, $sql);
while($row = mysqli_fetch_array($result))
{
$detail = str_pad($rekod,0).str_pad($bank_code,7).str_pad($row['nombor_akaun'],16).str_pad($row['nama'],40);
}
fwrite($fo,trim($header).PHP_EOL.$detail);
fclose($fo);
In your code you are overwriting the value of $detail each time round the loop with the value in while ..
you should use .= to append each row to your string
while($row = mysqli_fetch_array($result)) {
$detail .= str_pad($rekod,0).str_pad($bank_code,7).str_pad($row['nombor_akaun'],16).
str_pad($row['nama'],40);
}
Hi,
The problem: I Have an Export from a Database, however it needs to extract data from two tables. I Achieve this with an inner join.
artikel is the table with the basic information. It contains the id, article number, name, type and package form.
article_content is the table which contains the text which is part of the article, however, there are multiple languages. Every Article has a row for each language.
The Export Code
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=artikeldatenbank-' . date("dmyhi") . '.csv');
$output = fopen('php://output', 'w');
$stmt = $db->prepare('SELECT artikel.id, artikel.artikel_nummer, artikel.artikel_name, artikel.artikel_packung, artikel.artikel_cat, article_content.article_text, article_content.article_recuse, article_content.article_spec FROM artikel INNER JOIN article_content ON article_content.article_id = artikel.artikel_nummer');
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc())
fputcsv($output, $row);
What I want to Achieve
I need every row from the article_content table by it's article in a single line, instead of multiple lines. Sorry for the links, but imgur doesn't let me upload these. (Don't know why)
What happens now (image): http://prntscr.com/ek86bn
What I Want (edited image): http://prntscr.com/ek87ct
What is the best way to achieve this? Is this possible on the way I do it now?
Skip the VIEW solution, Solve it by code, my suggestion is
$result = $stmt->get_result();
$artikeID = '';
$newRow = [];
while ($row = $result->fetch_assoc())
{
if($artikeID != $row['id'])
{
if(!empty($newRow))
{
fputcsv($output, $newRow);
$newRow = [];
}
$artikeID = $row['id'];
$newRow = $row;
}
else
{
$newRow['title-'.$row['id']] = $row['artikel_name'];
$newRow['content-'.$row['id']] = $row['article_text'];
}
}
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
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.
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).