【问题标题】:Populate DataTable with data from MySQL and PHP使用来自 MySQL 和 PHP 的数据填充 DataTable
【发布时间】:2017-09-07 15:42:50
【问题描述】:

我正在尝试使用来自 MySQL 的数据填充我的数据表,但不知道如何执行此操作。我希望能够在定向到页面后填充 DataTable,然后用户可以单击一行并将该行的数据用于用户将被重定向到的下一页。这是我目前所拥有的:

<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 文件:

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

【问题讨论】:

标签: php jquery mysql datatables


【解决方案1】:

改用 dataTables API

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

【讨论】:

  • 感谢您的回答!我确信这也有效,但我想我想出了一个解决方案,即通过将行中的数据通过 URL 传递到 PHP GET 变量中来传递数据。
猜你喜欢
  • 2020-03-05
  • 2020-08-07
  • 2012-03-12
  • 2019-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-22
  • 2014-03-10
相关资源
最近更新 更多