简体   繁体   English

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

[英]Export only certain columns from mySQL database using PHP file

I've created a .php file that users will access via hyperlink within our web portal to download a database to a CSV file and I can get it to download the entire database but I only want to export the columns FirstName LastName Postcode & Email. 我已经创建了一个.php文件,用户可以通过我们的Web门户中的超链接访问该文件,以将数据库下载到CSV文件,可以下载整个数据库,但是我只想导出FirstName LastName Postcode&Email列。

What do I add/amend to the code below to do this? 我要在下面的代码中添加/修改什么呢? I assume it's in the mysql_query line but can't figure out the command todo this. 我假设它在mysql_query行中,但无法找出执行此操作的命令。

    <?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;

?>

Just edit the 只需编辑

select *

bit, like 有点像

select FirstName, LastName, Postcode, Email from $table

(and try not to use the deprecated mysql_* functinons, use PDO instead if possible). (并且尽量不要使用不推荐使用的mysql_*函数,请尽可能使用PDO)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM