1

I have an array containing column names of a table i want to create which i got from an excel sheet.

I tried something like this

$sql = "CREATE TABLE IF NOT EXISTS ".$month."-".date('Y')."(
    ".foreach($tableColumnNames as $columnName){
         echo $columnName." VARCHAR(200) NULL,";
      }
."
)";

It returns error saying Parse error: syntax error, unexpected 'foreach' same thing with while loops

How can i create Table with column names i have in an array. And How can i set each column data type unique (INT,VARCHAR,..)

1
  • you shouldent use echo, you want to concatenate the values Commented Nov 22, 2015 at 20:09

1 Answer 1

2

you want to build the sql string like so:

$sql = "CREATE TABLE IF NOT EXISTS ".$month."-".date('Y')."(";

    foreach($tableColumnNames as $columnName){
         $sql .= $columnName." VARCHAR(200) NULL,";
      }
$sql=rtrim($sql,',');//remove last comma
$sql .=")";
Sign up to request clarification or add additional context in comments.

5 Comments

How can i remove comma(,) from sql last column name else it give me errors.
refresh, i added that in
it removes comma(,) from whole string not just from last column
are you sure you put it in the right place? it is outside the foreach
Sorry My mistake.. it was inside loop. Now everything works fine

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.