根据表单的多选框生成动态表

时间:2013-07-09 18:22:18

标签: php dynamic html-table

我一直在努力想清楚这一点,虽然很接近,但我无法解决问题。我的代码如下......

 <?php
include('functions.php');
connect();
if (isset($_POST['submit'])){
    $fieldName = $_POST['fieldName'];
    foreach($fieldName AS $key=>$values){
        $fieldList .= $values;

    }
    $fieldList = implode(',', $fieldName); //comma separated list
    echo $rowList;
    $sql = mysql_query("SELECT ".$fieldList." FROM members");
    $row = mysql_fetch_assoc($sql);
    echo "<table>";
    echo "<tr>";
    foreach ($row as $col => $value) {
        echo "<th>";
        echo $col;
        echo "</th>";
    }
    echo "</tr>";
    while ($row = mysql_fetch_assoc($sql)){
        echo "<tr><td>".$row['city']."</td><td>".$row['firstName']."</td><td>".$row['cellPhone']."</td></tr>";//***HOPING TO GENERATE THIS DYNAMICALLY WITH VARIABLES...MAYBE ANOTHER FOREACH???
    }
    echo "</table>";

}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head>
</head>
<body>
<form action="" method="post" name="form">
<select name="fieldName[]" multiple="yes" id="fieldName">
    <option value="">Select all that apply</option>
    <option value="city">City</option>
    <option value="lastName">Last Name</option>
    <option value="firstName">First Name</option>
    <option value="state">State</option>
    <option value="cellPhone">Cell Phone</option>
</select>           
<input type="submit" name="submit" value="SUBMIT"/>
</form>
</body>
</html>

我非常接近,但我不明白如何创建位于上面的while循环之间的“echo语句”。我的猜测是,我会做类似于...... $fieldList .= $values;的事情,根据用户在下拉框中选择的项目数量,语句将根据需要增长。

1 个答案:

答案 0 :(得分:0)

我只是想通了。请在下面找到我用来生成我正在寻找的动态表列表的代码...

while ($row = mysql_fetch_assoc($sql)){
    echo "<tr>";
    foreach ($fieldName as $value){
        echo "<td>".$row[$value]."</td>";
    }
    echo "</tr>";
}

我希望这可以帮助那些尝试创建简单报告工具的人。