【问题标题】:How to get field name using the improved MySQL (MySQLI)? [duplicate]如何使用改进的 MySQL (MySQLI) 获取字段名称? [复制]
【发布时间】:2017-08-17 03:21:21
【问题描述】:

以下是我用来将 MySQL 表转换为 csv 输出的 PHP 代码。但是,我不知道如何将 MySQL_field_name 转换为 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()

【问题讨论】:

    标签: php mysql mysqli


    【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-05
      • 2015-03-11
      • 1970-01-01
      • 2021-04-02
      相关资源
      最近更新 更多