douweidao3882 2017-04-12 03:25
浏览 47
已采纳

使用来自MySQL和PHP的数据填充DataTable

I am trying to populate my Datatable with data from MySQL but can't figure out how to do so. I want to be able to populate the DataTable once directed to the page, then user can click on a row and use that row's data for the next page the user will be redirected to. This is what I have so far:

<table id="example" class="display" cellspacing="0" width="100%">
<thead>
    <tr>

        <th>Name</th>
        <th>Age</th>
        <th>Gender</th>
    </tr>

</thead>
<tfoot>
    <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Gender</th>
    </tr> 
</tfoot>
<tbody>
    <tr>
        <td> Placeholder1</td>
        <td> Placeholder2</td>
        <td> Placeholder3</td>
    </tr>
    <tr>
        <td> Placeholder1</td>
        <td> Placeholder2</td>
        <td> Placeholder3</td>
    </tr>
    <tr>
        <td> Placeholder1</td>
        <td> Placeholder2</td>
        <td> Placeholder3</td>
    </tr>
</tbody>
</table>

<script>


$(document).ready(function() {
var table = $('#example').DataTable();

$('#example tbody').on('click', 'tr', function () {
    var data = table.row( this ).data();
    alert( 'You clicked on '+data[0]+'\'s row' );
} );
} );
</script>

PHP FILE:

<?php

include('connection.php');



 $sql = "SELECT ID, Name, Age, Gender FROM DBTABLE";


$response = mysqli_query($db, $sql);


if($response)
{
    echo '<table>';

   while($row = mysqli_fetch_array($response))
    {

       echo '<tr><td align="left">' .
            $row['Name'] . '</td><td align="left">' .
            $row['Age']  '</td><td align="left">' .
            $row['Gender'] . '</td><td align="left">';


       echo '</tr>';
    }

   echo '</table>';

  }
else
{
    echo "Couldn’t issue database query<br />";
    echo mysqli_error($db);
}






// Close connection to the database
mysqli_close($db);
?>
  • 写回答

1条回答 默认 最新

  • dth62818 2017-04-12 05:49
    关注

    Use the dataTables API instead

    var table = $('#example').DataTable({
      ajax: {
        url: 'phpfile.php'
      },
      columns: [
        { data: 'Name' },
        { data: 'Age' },
        { data: 'Gender' }
      ]
    });
    

    phpfile.php

    ...
    $data = array();
    if ($response) {
      while($row = mysqli_fetch_assoc($response)) {
        $data[] = $row;
      }
    }
    echo json_encode(array('data' => $data));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗