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