2013-09-21 72 views
0

我試圖檢索存儲在未知數量的mySQL數據庫行中的數據並使用HTML顯示它們。目前我可以顯示一行數據。如何顯示多個SQL數據庫行的內容

每一行都有一個唯一的ID號,我打算通過比較這個數字與變量counter進行迭代。但是這會讓我在HTML中顯示結果的問題。此刻,我只是回顯包含行中數據的變量。然而,我想創建一個HTML列表,其長度取決於表中有多少行。

這裏是我從數據庫中檢索行當前的PHP代碼:

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

回答

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

$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

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