Reputation: 105
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:
<?php
//print_r($_GET);
$col_names=[]; //this will store column names received from user
$col_types=[];//this will store column data types selected by user
if(isset($_GET['col_num'])){
$table_name=$_GET['table_name'];
$n=$_GET['col_num'];
for($i=0;$i<$n;$i=$i+1){
$index_names = "col".$i;
$index_type = "type".$i;
$col_names[$i] = $_GET[$index_names];
$col_types[$i] = $_GET[$index_type];
}
}
$con=mysqli_connect('localhost','root');
if(!$con){
die("Error conncecting: ". mysqli_error($con));
}
else{
mysqli_select_db($con,'temp');
$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.
*/
mysqli_query($query);
}
?>
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?
Upvotes: 0
Views: 6486
Reputation: 2098
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
mysqli_query($query);
Upvotes: 2