我正在尝试从mysql数据库中检索列名。我可以得到这样的列名:
Array ( [id] => id [BSPKey] => BSPKey [PrintPost] => PrintPost [Barcode] => Barcode [FirstName] => FirstName [LastName] => LastName [Add1] => Add1 [Add2] => Add2 [Suburb] => Suburb [State] => State [Zip] => Zip [Team] => Team [Dteam] => Dteam [Fteam] => Fteam [DPID] => DPID [Error] => Error [Address1] => Address1 [Address2] => Address2 [correct3] => correct3 [correct4] => correct4 [correct5] => correct5 [fcorrect] => fcorrect [bspprint] => bspprint )
得到这个我使用这个脚本
$qColumnNames = mysqli_query($conn,"SHOW COLUMNS FROM newdata");
$numColumns = mysqli_num_rows($qColumnNames);
$x = 0;
while ($x < $numColumns)
{
$colname = mysqli_fetch_row($qColumnNames);
$col[$colname[0]] = $colname[0];
$x++;
}
print_r($col);
但我只想要列名,并希望像这样填充html <select>
元素
<select name="column_name[]" multiple="multiple">
<option selected="selected" value="id">id</option>
<option selected="selected" value="BSPKey">BSPKey</option>
<option selected="selected" value="PrintPost">PrintPost</option>
<option selected="selected" value="Barcode">Barcode</option>
<option selected="selected" value="FirstName">FirstName</option>
<option selected="selected" value="LastName">LastName</option>
<option selected="selected" value="Add1">Add1</option>
<option selected="selected" value="Add2">Add2</option>
<option selected="selected" value="Suburb">Suburb</option>
<option selected="selected" value="State">State</option>
<option selected="selected" value="Zip">Zip</option>
<option selected="selected" value="Team">Team</option>
<option selected="selected" value="Dteam">Dteam</option>
<option selected="selected" value="Fteam">Fteam</option>
<option selected="selected" value="DPID">DPID</option>
<option selected="selected" value="Error">Error</option>
<option selected="selected" value="Address1">Address1</option>
<option selected="selected" value="Address2">Address2</option>
<option selected="selected" value="correct3">correct3</option>
<option selected="selected" value="correct4">correct4</option>
<option selected="selected" value="correct5">correct5</option>
<option selected="selected" value="fcorrect">fcorrect</option>
<option selected="selected" value="bspprint">bspprint</option>
</select>
希望有人有一个简单的解决方案。
答案 0 :(得分:1)
你只需要迭代最后得到的数组($col
)。只需在此数组上使用foreach
并填充HTML
,就像这样,
<select name="column_name[]" multiple="multiple">
<?php
foreach($col as $key=>$val) {
?>
<option selected="selected" value="<?php echo $key; ?>"><?php echo $val; ?></option>
<?php
}
?>
</select>
上述代码的结果与您需要的相同。它只是使用<option>
和key
为数组的每个元素显示value
。