0

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?

4
  • 2
    php syntax is not good.. try some tutorial how to concat string Commented Mar 1, 2017 at 5:52
  • What is CREATE TABLE $table_name ( for($i=0; $i<$n ;$i=$i+1) suppose to be doing? Please indent your code and use parameterized queries. Commented Mar 1, 2017 at 5:53
  • I've gone through many tutorials but i am not able to pick the flaw! Also i'm not sure on how to add a comma after each column name and data type @ChetanAmeta Commented Mar 1, 2017 at 5:54
  • @chris85 I have updated the question details! Commented Mar 1, 2017 at 5:59

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.