PHP和MySQL的动态表单帮助

时间:2010-04-23 02:59:48

标签: php mysql dynamic-data

以下代码的工作原理是将文件中的记录插入MySQL,但只有在文件中的列的排序方式与数据库中的方式相同时才能正确执行。我希望用户能够选择与其文件中每列对应的下拉列表,以便与数据库中的列匹配(数据库具有电子邮件地址,名字,姓氏)。我不知道如何做到这一点。有什么想法吗?

    <?php

$lines =file('book1.csv');

foreach($lines as $data)
{
list($col1[],$col2[],$col3[])
= explode(',',$data);
}

$i = count($col1);

if (isset($_POST['submitted'])) {

DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', 'password');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'csvimport');

// Make the connection:
$dbc = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);



for($d=1; $d<$i; $d++) {


$q = "INSERT into contacts (email, first, last) VALUES ('$col3[$d]', '$col1[$d]', '$col2[$d]')";
$r = @mysqli_query ($dbc, $q);

}
}

echo "<form action =\"handle2.php\" method=\"post\">Email<br />
<select name =\"email\">
<option value='col1'>$col1[0]</option>
<option value='col2'>$col2[0]</option>
<option value='col3'>$col3[0]</option>
</select><br /><br />
First Name <br />
<select name=\"field2\">
<option value='col1'>$col1[0]</option>
<option value='col2'>$col2[0]</option>
<option value='col3'>$col3[0]</option>
</select><br /><br />
Last Name <br />
<select name=\"field3\">
<option value='col1'>$col1[0]</option>
<option value='col2'>$col2[0]</option>
<option value='col3'>$col3[0]</option>
</select><br /><br />
<input type=\"submit\" name=\"submit\" value=\"Submit\" />

<input type=\"hidden\" name=\"submitted\" value=\"TRUE\" />

</form>";


?>

1 个答案:

答案 0 :(得分:0)

从你已经拥有的东西开始,你可能想要做这样的事情......

$table_name = "contacts";

// You'll want the array to look like this:
$cols_in_csv_file = array(
   'col_header_1',
   'col_header_2',
   'col_header_3',
);

$csv_select_menu = '<select name="csv_cols[]">';
foreach ($cols_in_csv_file as $col) {
   $csv_select_menu .= '<option value="' . htmlentities($col) . '">' . $col . '</option>';
}
$csv_select_menu .= '</select>';

$result = mysqli_query("SHOW COLUMNS FROM " . $table_name, $q);
$fields = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
   $fields[] = $row['Field'];
}

echo '<table><tr>';
foreach ($fields as $field) {
   echo '<td>' . $field . $csv_select_menu . '</td>';
}
echo '</tr></table>';