简体   繁体   English

如何使用php动态创建mysql表?

[英]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. 我有一个列名和列数据类型的数组,现在我希望使用这两个数组创建一个mysql表。 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? 现在,我知道编写的“创建查询”出了点问题,但是我无法弄清楚如何构造查询。此外,在有多列的情况下,我应该如何放置逗号?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM