我有一个列名和列数据类型的数组,现在我希望使用这两个数组创建一个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);
}
?>
现在我知道我写的“创建查询”出了问题,但是我无法弄清楚如何构建查询。另外,如果有多列,我应该如何放置逗号?
答案 0 :(得分: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);