Kenil Patel Kenil Patel -4 years ago 155
MySQL Question

How to create mysql table dynamically using php?

I have an array of column names and column data types and now i wish to create a mysql table using these two arrays. Here's my code so far:


$col_names=[]; //this will store column names received from user
$col_types=[];//this will store column data types selected by user



$index_names = "col".$i;
$index_type = "type".$i;
$col_names[$i] = $_GET[$index_names];
$col_types[$i] = $_GET[$index_type];


die("Error conncecting: ". mysqli_error($con));

$query = "CREATE TABLE $table_name (
for($i=0; $i<$n ;$i=$i+1)
echo "$col_names[$i]" . " " . "$col_types[$i]" . "(10)"
If suppose the col_names array contains : [Name,Age] and col_types contains: [Varchar,Int] then i need these two attributes to be incorporated in my Create query and so i have put them in a for loop.


Now i know that something's wrong with the "Create Query" that i have written but i am not able to figure out how to frame the query.Also how should i place the comma in case of multiple columns?

Answer Source

You are doing wrong, Use something like this,

$query = "CREATE TABLE $table_name ( ";
for($i=0; $i<$n ;$i=$i+1)
  $query .= "$col_names[$i]" . " " . "$col_types[$i]" . "(10)"  ;
$query .= " ); ";
echo $query;//output and check your query
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download