如何从数据库检索数据,以csv格式在网页上显示? [英] How to retrieve data from database to display it in csv format on a webpage?

查看:182
本文介绍了如何从数据库检索数据,以csv格式在网页上显示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上,我想在网页上以csv格式显示数据。数据存储在数据库中的消息字段中。
数据为:

Actually I want to display data in csv format on a web page . Data is stored in message field in the database. The data is :

data    count 
120     80
140     50
170     100
150     70
180     120

csv格式的网页,用逗号分隔,如:data,count。
我在其他网站上发现这个代码,而不是在网页上显示数据,它使csv文件在文件夹中,并将数据存储在其中。
这里是代码:


I want to display this data on a webpage in csv format separated by comma like: data , count . I found this code on some other site but rather than displaying data on a webpage it make the csv file in folder and store the data in it . here is the code:

// open connection to mysql database   
$connection = mysqli_connect($host, $username, $password, $dbname) or 
die("Connection Error " . mysqli_error($connection));

// fetch mysql table rows   
$sql = "select message from wholesaler";

$result = mysqli_query($connection, $sql) or die("Selection Error " . mysqli_error($connection));

$fp = fopen('books.csv', 'w');
while($row = mysqli_fetch_assoc($result)) {
    fputcsv($fp, $row);
}    
fclose($fp);

//close the db connection    
mysqli_close($connection);

任何人都可以告诉我解决这个问题的步骤吗?

Can anyone tell me the steps to resolve it ?

推荐答案

您提供的代码使用循环将数据保存到CSV文件中。因为你不需要将它保存在一个文件,那么你必须替换这个循环与一些代码打印输出行。

Code you provided use the loop to save data into CSV file. Because you don't need to save it in a file then you have to replace this loop with some code printing rows on your output.

根据你的代码,你需要替换此零件

According to your code you need to replace this part

$fp = fopen('books.csv', 'w');

while($row = mysqli_fetch_assoc($result))
{
    fputcsv($fp, $row);
}

例如

while($row = mysqli_fetch_assoc($result)) { 
    //we need to split your message into array
    $csvRows = explode("\n", $row['message']);

    $head = [];
    if (array_key_exists(0, $csvRows)) {
        $head = explode(' ', trim($csvRows[0]));
    }

    $data = [];
    for ($i = 1; $i < count($csvRows); $i++) {
        $data[] = explode(' ', trim($csvRows[$i]));
    }

    //print recognized headers
    echo '<table width="100%"><tr>';
    foreach ($head as $h) {
        echo "<th>{$h}</th>";
    }
    echo '</tr>';

    //print your csv row as table row
    foreach ($data as $r) {
        echo '<tr>';
        foreach ($r as $v) {
            echo "<td>{$v}</td>";
        }
        echo '</tr>';
    }
    echo '<table>';
}

这篇关于如何从数据库检索数据,以csv格式在网页上显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆