使用PHP文件仅从mySQL数据库导出某些列

时间:2015-09-03 14:05:01

标签: php mysql

我创建了一个.php文件,用户可以通过我们门户网站中的超链接访问该文件,将数据库下载到CSV文件,我可以让它下载整个数据库,但我只想导出列FirstName LastName Postcode &安培;电子邮件。

我在下面的代码中添加/修改了什么来执行此操作?我假设它在mysql_query行中,但无法找出todo这个命令。

    <?php

// Database Connection

$host="localhost:/tmp/mysql5.sock";
$uname="dbo1234567";
$pass="password";
$database = "db1234567"; 

$connection=mysql_connect($host,$uname,$pass); 

echo mysql_error();

//or die("Database Connection Failed");
$selectdb=mysql_select_db($database) or 
die("Database could not be selected"); 
$result=mysql_select_db($database)
or die("database cannot be selected <br>");

// Fetch Record from Database

$output = "";
$table = "tbl_Coach"; // Enter Your Table Name 
$sql = mysql_query("select * from $table");
$columns_total = mysql_num_fields($sql);

// Get The Field Name

for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";

// Get Records from the table

while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}

// Download the file

$filename = "coachdb.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);

echo $output;
exit;

?>

1 个答案:

答案 0 :(得分:0)

只需编辑

即可
select *

位,如

select FirstName, LastName, Postcode, Email from $table

(并尝试不使用已弃用的mysql_*功能,如果可能,请使用PDO。)

相关问题