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?

StackOverflow https://stackoverflow.com/questions/23181241

  •  06-07-2023
  •  | 
  •  

Question

I want to create a table in mysql where the number of fields in the table equals the number of columns in the excel file.

$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());
}

I try that code, but not working. Thank you.

Was it helpful?

Solution

The problem is the column name syntax you chose: square brackets are not valid inside column names. So Kol[$col] is invalid, you can do something like Kol_$col instead.

For reasons of coding style I would advise to use sprintf() for this:

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

Also note the lowercase 'k' in the column name. It has proven to prevent annoying errors not to user uppercase characters in identifier names.

You can simplify your code by using phps implode() function, 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 ));

OTHER TIPS

A bit of restructing your code. Try the following -

1) Convert your excel file to csv.

2) Run the function csv_to_array()
         input - filename.csv
         output - array of column names

3) Run the foreach() loop

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());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top