如何显示多个SQL数据库行的内容

时间:2013-09-21 12:03:43

标签: php html mysql sql html5

我正在尝试检索存储在未知数量的mySQL数据库行中的数据,并使用HTML显示它们。目前我可以显示一行数据。

每一行都有一个唯一的ID号,我打算通过将这个数字与变量counter进行比较来迭代。但这会让我想到用HTML显示结果的问题。目前我只是回显包含行数据的变量。但是,我想创建的是一个HTML列表,其长度会根据表中的行数而增加。

以下是我目前用于从数据库中检索行的PHP代码:

$sql = "SELECT * FROM project_tasks WHERE project_name='$proj_name' AND task_id='$counter'"; 
$query = mysqli_query($db_conx, $sql);
$row = $query->fetch_assoc();
$task_id = $row["task_id"];
$proj_name = $row["project_name"];
$task_name = $row["task_name"];
$task_importance = $row["task_importance"];
$task_description = $row["task_description"];
$task_deadline = $row["task_deadline"];
$task_members = $row["task_members"];
$task_budget = $row["task_budget"];

目前我只是使用以下代码在HTML中显示一些结果:

<div id="inner_container">
            <?php echo "$task_id $proj_name $task_name $task_deadline"; ?>
            </div>

2 个答案:

答案 0 :(得分:1)

$sql = "SELECT * FROM project_tasks WHERE project_name='$proj_name' AND task_id='$counter'"; 
$query = mysqli_query($db_conx, $sql);

while($row = $query->mysqli_fetch_assoc()) {

  $task_id = $row["task_id"];
  $proj_name = $row["project_name"];
  $task_name = $row["task_name"];
  $task_importance = $row["task_importance"];
  $task_description = $row["task_description"];
  $task_deadline = $row["task_deadline"];
  $task_members = $row["task_members"];
  $task_budget = $row["task_budget"];

  echo "$task_id $proj_name $task_name $task_deadline";
}

答案 1 :(得分:1)

由于您使用fetch_assoc构建了一个关联数组,所以您需要做的就是遍历该数组。 http://php.net/manual/en/mysqli-result.fetch-assoc.php上的OO示例应该可以满足您的需求。一个简单的例子:

$sql = "SELECT * FROM project_tasks WHERE project_name='$proj_name' AND task_id='$counter'"; 
$query = mysqli_query($db_conx, $sql);

echo '<div id="inner_container">';
    while ($row = $query->fetch_assoc()) {
        $proj_name = $row["project_name"];
        $task_name = $row["task_name"];
        $task_deadline = $row["task_deadline"];

        echo "$task_id $proj_name $task_name $task_deadline";
    };

    /* free result set */
    $row->free();

echo '</div>;