2017-03-01 37 views
-1

我有一個列名和列數據類型的數組,現在我想用這兩個數組創建一個mysql表。這裏是我到目前爲止的代碼:如何使用php動態創建mysql表?

<?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); 
} 
?> 

現在我知道什麼是錯的「創建查詢」,我已經寫了,但我無法弄清楚如何框定query.Also我應該如何放置逗號在多列的情況下?

+2

PHP語法也不好..嘗試一些教程如何Concat的字符串 –

+0

什麼是'CREATE TABLE $表名( 爲($ i = 0 ; $ i <$ n; $ i = $ i + 1)'假設要做什麼?請縮進您的代碼並使用參數化查詢 – chris85

+0

我已經經歷了很多教程,但我無法挑選缺陷!我不確定如何在每個列名和數據類型後添加逗號@ChetanAmeta –

回答

1

你做錯了,使用這樣的事情,

$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); 
+1

Thanx很多@ detective404 ..那工作.. 但是,只有在兩個數組中都有一個值的情況下才有效。我該如何使用逗號修改多個值的代碼? –

+0

我得到了答案! 非常感謝! @ detective404 –