[英]CSV Export: Multiple Database Rows to Single Row
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. artikel
是带有基本信息的表格。 It contains the id, article number, name, type and package form. 它包含ID,商品编号,名称,类型和包装形式。
article_content
is the table which contains the text which is part of the article, however, there are multiple languages. article_content
是包含文章一部分的文本的表,但是,有多种语言。 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. 我需要
article_content
表中的每一行都位于同一行中,而不是多行中。 Sorry for the links, but imgur doesn't let me upload these. 抱歉,链接,但是imgur不允许我上传这些链接。 (Don't know why)
(不知道为什么)
What happens now (image): http://prntscr.com/ek86bn 现在会发生什么(图片): http : //prntscr.com/ek86bn
What I Want (edited image): http://prntscr.com/ek87ct 我想要什么(编辑图像): 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 跳过VIEW解决方案,通过代码解决,我的建议是
$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'];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.