dongxiaoxiao1983 2014-09-12 22:28
浏览 62
已采纳

使用动态创建的表单创建MySQL表

I have been trying to create a form that allows users to create a MySQL table using a dynamically generated from. The user initially inputs the desired table name, and then the number of rows they want. When they type the number, an equal amount of form rows are created. Each field created has a name like "fieldName[]". My hope was to create an array, and then use the created array to complete the table creation query. I could get it to work how I wanted if I used something like:

$myarray = array("key1"=>array($fieldName[0],$fieldName[1],$fieldName[2]),
    "key2"=>array($fieldType[0],$fieldType[1],$fieldType[2]),
     "key3"=>array($fieldLength[0],$fieldLength[1],$fieldLength[2]));

Javascript Dynamic Row Creator:

function numFields(nums) {
var str = "";
for (i = 0; i < nums; i++) {
    str += '<p><label style="padding-left:10px;">Name: <input type="text" value="fred'+(i+1)+'" name="Name[]" id="newtblname'+(i+1)+'" /></label></p>';
}
document.getElementById('Fields').innerHTML = str;
}

And the PHP:

if (isset($_GET['tabletest'])) {
$Name=$_POST['Name'];
$x=0;
foreach($Name as $value) {
    $names= $value;
    echo $Name[$x];
    echo "<br>";
    $x++;
}
}

Solution: Here is the code I got to work:

$fieldsNum = $_POST['fieldsNum'];
$tblName = $_POST['tblName'];
$nameArray=$_POST['Name'];
$x = 0;

$tables = 'CREATE TABLE '.$tblName.' (';
foreach($nameArray as $value) {
$tables .= $value . " CHAR(200)"; 
$x++;
if($x<$fieldsNum) {
$tables .= ", ";
}

}
$tables .= ');';

echo $tables;
}
  • 写回答

1条回答 默认 最新

  • duanci1939 2014-09-16 15:12
    关注

    You need to have a form in your HTML like:

    <form method="post" action="tableCreate.php">
    <input type="text" name="fieldName[]"><br>
    .
    .
    .
    <button type="submit">Go!</button>
    </form>
    

    Then in tableCreate.php you should see them as

    $tableArray = $_POST['fieldName'];
    $tables = 'CREATE TABLE tblName (';    
    
    foreach($tableArray as $value) {
    $tables .= $value . " CHAR(200), ";
    }
    $tables .= ');';
    
    echo $tables;
    

    This would loop through the array and put each table name in the string which you could later use for creating the tables.

    (I can not test this at the moment, but it should be fine).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)