2016-10-05 67 views
-1

我正在嘗試輸出PHP中MySQL表格的結果。我對基於Web的編程有一般的理解,但不足以調試我的代碼。我知道SQL很好,數據庫鏈接到我的網站,只是將它發佈到表格中。我會發布的代碼,並希望得到一些幫助:使用PHP從鏈接的MySQL表中輸出表格

<?php 

     $sql = "SELECT player_name AS 'Name', 
     position AS 'Position', 
     team AS 'Team', 
     opp AS 'Opponent' 
     FROM `dbname` 
     WHERE position = 'QB'"; 

     $stmt = $db->query($sql); 

     if($stmt-> num_rows > 0) { 
      echo "<table class='table'>"; 
      echo "<thead class='thead-inverse'>"; 
      echo "<tr><th>Name</th><th>Position</th><th>Team</th><th>Opponent</th>"; 
      echo "</thead>"; 
      echo "<tbody>"; 
      while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
       echo "<tr><td>"; 
       echo $row['Name']; 
       echo "</td><td>"; 
       echo $row['Position']; 
       echo "</td><td>"; 
       echo $row['Team']; 
       echo "</td><td>"; 
       echo $row['Opponent']; 
       echo "</td></tr>"; 

     } 
     echo "</tbody>"; 
     echo "</table>"; 
     } 
     else { 
      echo "No Results"; 
     } 

我從這得到的所有是沒有結果輸出。

回答

0

您忘記了用雙引號關閉查詢。

<?php 

    $sql = "SELECT player_name AS 'Name', 
    position AS 'Position', 
    team AS 'Team', 
    opp AS 'Opponent' 
    FROM `dbname` 
    WHERE position = 'QB'"; 

    $stmt = $db->query($sql); 
    $stmt -> execute(); 

    if($stmt-> num_rows > 0) { 
     echo "<table class='table'>"; 
     echo "<thead class='thead-inverse'>"; 
     echo "<tr><th>Name</th><th>Position</th><th>Team</th><th>Opponent</th>"; 
     echo "</thead>"; 
     echo "<tbody>"; 
     while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
      echo "<tr><td>"; 
      echo $row['Name']; 
      echo "</td><td>"; 
      echo $row['Position']; 
      echo "</td><td>"; 
      echo $row['Team']; 
      echo "</td><td>"; 
      echo $row['Opponent']; 
      echo "</td></tr>"; 

    } 
    echo "</tbody>"; 
    echo "</table>"; 
    } 
    else { 
     echo "No Results"; 
    } 

添加$stmt -> execute();

您還可以在execute部分

+0

我縮短了查詢,使之更容易輸入後使用$stmt -> store_result();,這是一個錯字。在實際的代碼中,我用引號關閉了查詢。該問題不在查詢中,而是將結果放入表格中。 –