繁体   English   中英

如何在mysql中创建表,其中表中的字段数等于php中excel文件中的列数?

[英]How to create a table in mysql where the number of fields in the table equals the number of columns in the excel file in php?

我想在mysql中创建一个表,其中表中的字段数等于excel文件中的列数。

$sSql = "";
for ($col = 1; $col <= $nrColumns; ++ $col) {
   if ($col < $nrColumns){
      $sSql = $sSql . " Kol[$col] VARCHAR(25), ";
   } else {
      $sSql = $sSql . " Kol[$col] VARCHAR(25)";
   }
}
echo "SQL = $sSql <br>";

$sqlCreate="CREATE TABLE temp_table ( $sSql )";

$result = mysql_query($sqlCreate, $connect);
if (!$result){
  die('Could not create table: ' . mysql_error());
}

我尝试该代码,但无法正常工作。 谢谢。

问题是您选择的列名语法:列名内的方括号无效。 所以Kol[$col]是无效的,您可以Kol_$col

出于编码风格的原因,我建议为此使用sprintf()

$sSql .= sprintf( ' kol_%s VARCHAR(25)', (int)$col );

还要注意列名中的小写字母“ k”。 事实证明,它可以防止讨厌的错误, 而不是标识符名称中的用户大写字符。

您可以使用phps implode()函数btw来简化代码:

$sCol = array();
for ($col = 1; $col <= $nrColumns; ++ $col)
   $sCol[] = sprintf( 'kol_%s VARCHAR(25)', (int)$col )
$sqlCreate = sprintf( 'CREATE TABLE temp_table (%s)', implode( ", ", $sCol ));

重构一下代码。 试试以下-

1)将您的Excel文件转换为CSV。

2)运行函数csv_to_array()
输入 -filename.csv
输出 -列名称数组

3)运行foreach()循环

function csv_to_array($filename='', $delimiter=',')
{
   if(!file_exists($filename) || !is_readable($filename))
      return FALSE;

   $header = NULL;
   $data = array();
   if (($handle = fopen($filename, 'r')) !== FALSE)
   {
      while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
      {
         $data = $row;
         break;         
      }
      fclose($handle);
   }
   return $data;
}

$columns = csv_to_array("myfile.csv");

$sql = "";
foreach($columns as $col)
{
  $sql .= $col." VARCHAR(25), ";
}

$query = "CREATE TABLE table_name 
          id int(20) NOT NULL AUTO_INCREMENT,
          $sql
          PRIMARY KEY (`id`)
         ";

$result = mysql_query($query, $connect);
if (!$result)
{
   die('Could not create table: ' . mysql_error());
}

暂无
暂无

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

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