2016-01-12 37 views
0

我見過很多類似的問題但他們都混淆了我,因爲我沒有使用$ wpdb變量來獲取數據。我正在使用簡單的PHP方式來獲取數據通過調用wordpress數據庫。但不知何故,它只返回一行。這裏是用於獲取數據的代碼行。MySql只返回一行同時獲取數據表格wordpress

$sql = "SELECT * FROM teacher_directory"; 
if($result = mysqli_query($link, $sql)){ 
if(mysqli_num_rows($result) > 0){ 
    echo "<table>"; 
     echo "<tr>"; 
      echo "<th>S. No.</th>"; 
      echo "<th>Name</th>"; 
      echo "<th>Designation</th>"; 
      echo "<th>Department</th>"; 
      echo "<th>Tele/Mob.No.</th>"; 
     echo "</tr>"; 
    while($row = mysqli_fetch_array($result)){ 
     echo "<tr>"; 
      echo "<td>" . $row['S. No.'] . "</td>"; 
      echo "<td>" . $row['Name'] . "</td>"; 
      echo "<td>" . $row['Designation'] . "</td>"; 
      echo "<td>" . $row['Department'] . "</td>"; 
      echo "<td>" . $row['Tele/Mob.No.'] . "</td>";    
     echo "</tr>"; 
    } 
    echo "</table>"; 

任何幫助或建議將是可觀的。

+0

你得到多個字段在實際查詢? – Milap

+0

mysqli_num_rows($ result)的結果是什麼 –

+0

我在輸出中得到了一個完整的單行。 – Rishabh

回答

0

使用這個WordPress查詢獲取從數據庫結果

global $wpdb; 
$results = $wpdb->get_results('SELECT * FROM teacher_directory WHERE 1', ARRAY_A ); 
if(!empty($results)){ 
    echo "<table>"; 
    echo "<tr>"; 
     echo "<th>S. No.</th>"; 
     echo "<th>Name</th>"; 
     echo "<th>Designation</th>"; 
     echo "<th>Department</th>"; 
     echo "<th>Tele/Mob.No.</th>"; 
    echo "</tr>"; 
    foreach($results as $row){ 
    echo "<tr>"; 
     echo "<td>" . $row['S. No.'] . "</td>"; 
     echo "<td>" . $row['Name'] . "</td>"; 
     echo "<td>" . $row['Designation'] . "</td>"; 
     echo "<td>" . $row['Department'] . "</td>"; 
     echo "<td>" . $row['Tele/Mob.No.'] . "</td>";    
    echo "</tr>"; 
    } 
    echo "</table>"; 
} 
+0

它也返回單行。 – Rishabh

+0

嗨Rishabh,你必須在'$ row [「title」]''中聲明你的數據庫列名。 如果我使用'wp_posts'表,那麼我必須聲明'$ row [「post_title」]'其中'post_title'是數據庫中的列名稱。 – Harsh

+0

它的工作!我只是從查詢中刪除'where 1'。現在它工作正常。謝謝.. – Rishabh

0

請使用$ WPDB類(具有直接訪問和操作的WordPress的數據庫功能):

global $wpdb; 
$sql = $wpdb->get_results("SELECT * FROM teacher_directory"); 
$results = $wpdb->get_results($sql) or die(mysql_error()); 
if($results) { 
echo "<table>"; 
    echo "<tr>"; 
     echo "<th>S. No.</th>"; 
     echo "<th>Name</th>"; 
     echo "<th>Designation</th>"; 
     echo "<th>Department</th>"; 
     echo "<th>Tele/Mob.No.</th>"; 
    echo "</tr>"; 
} 
foreach($results as $row) { 
    echo "<tr>"; 
     echo "<td>" . $row['S. No.'] . "</td>"; 
     echo "<td>" . $row['Name'] . "</td>"; 
     echo "<td>" . $row['Designation'] . "</td>"; 
     echo "<td>" . $row['Department'] . "</td>"; 
     echo "<td>" . $row['Tele/Mob.No.'] . "</td>";    
    echo "</tr>"; 
} 
echo "</table>"; 
+0

需要wp-db.php中的參數警告。沒有顯示。 – Rishabh