如何使用php显示上传的csv文件数据

时间:2014-09-19 09:28:31

标签: php mysql csv

目前我正在php中创建一个上传CSV文件并将数据插入数据库的项目。 在插入数据之前,我需要以表格格式显示数据。

我使用此代码上传和插入数据。

if (isset($_POST['submit'])) 
{
$name = $_POST['camname'];
if (is_uploaded_file($_FILES['filename']['tmp_name'])) 
{
    echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
}

Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
    $import="INSERT into uploadmail(name,email) values('$name','$data[0]')";
    mysql_query($import) or die(mysql_error());
}

fclose($handle);
}

此编码成功将数据插入数据库,但我需要以表格格式显示数据。所以请提出任何建议。

感谢先生。

1 个答案:

答案 0 :(得分:3)

只需用此替换您的代码即可。数据将保存到DB并将同时显示。 我在代码中以表格格式代码添加了显示数据。

if (isset($_POST['submit'])) 
{
$name = $_POST['camname'];
if (is_uploaded_file($_FILES['filename']['tmp_name'])) 
{
    echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
}

Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
echo "<table>\n<tr><th>Name</th><th>Email</th></tr>";
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
    echo "<tr>";
    $import="INSERT into uploadmail(name,email) values('$name','$data[0]')";

    echo "<td>".$name."</td><td>".$data[0]."</td>";
    mysql_query($import) or die(mysql_error());
    echo "</tr>";
}
echo "\n</table>";
fclose($handle);
}