2017-03-24 73 views
0

以下是我用來將MySQL錶轉換爲csv輸出的PHP代碼。但是,我無法弄清楚如何將MySQL_field_name轉換爲MySQLI中的等價物。任何人都可以協助如何使用改進的MySQL(MySQLI)獲取字段名稱?

<?php 
/* vars for export */ 
// database record to be exported 
$db_record = 'manufacturing_'; 
// optional where query 
$where = 'WHERE 1 ORDER BY 1'; 
// filename for export 
$csv_filename = 'db_export_'.$db_record.'_'.date('Y-m-d').'.csv'; 
// database variables 
$hostname = "localhost"; 
$user = "XXXXXXXXX"; 
$password = "XXXXXXXXX"; 
$database = "XXXXXXXXX"; 
// Database connecten voor alle services 
$connection = mysqli_connect($hostname, $user, $password) or die('Could not connect: ' . mysqli_error()); 

mysqli_select_db($connection, $database) or die ('Could not select database ' . mysqli_error()); 
// create empty variable to be filled with export data 
$csv_export = ''; 
// query to get data from database 
$query = mysqli_query($connection, "SELECT * FROM ".$db_record." ".$where); 
$field = mysqli_num_fields($query); 
// create line with field names 
for($i = 0; $i < $field; $i++) { 
    $csv_export.= mysqli_field_name($connection, $query,$i).';'; 
} 
// newline (seems to work both on Linux & Windows servers) 
$csv_export.= ' 
'; 
// loop through database query and fill export variable 
while($row = mysqli_fetch_array($connection, $query)) { 
    // create line with field values 
    for($i = 0; $i < $field; $i++) { 
    $csv_export.= '"'.$row[mysqli_field_name($connection, $query,$i)].'";'; 
    } 
    $csv_export.= ' 
'; 
} 
// Export the data and prompt a csv file for download 
header("Content-type: text/x-csv"); 
header("Content-Disposition: attachment; filename=".$csv_filename.""); 
echo($csv_export); 
?> 

錯誤消息:

致命錯誤:調用未定義功能mysqli_field_name()

回答

-1

您可以從INFORMATION_SCHEMA用這樣的查詢得到這個相關信息。您只需更改TABLE_SCHEMA和TABLE_NAME

SELECT COLUMN_NAME 
FROM information_schema.columns 
WHERE TABLE_NAME ='owner' AND TABLE_SCHEMA='test' 
ORDER BY ORDINAL_POSITION; 
相關問題