이 튜토리얼에서는 PHP 및 MySQL과 함께 부트스트랩 5 기반 데이터 테이블을 사용하여 동적 목록을 만드는 방법을 배웁니다. jQuery AJAX 메서드를 사용하여 MySQL에서 레코드를 가져오고 있습니다. 또한 jquery datatable을 사용하여 Ajax 기반 정렬 및 검색을 통합했습니다.
jQuery DataTables는 간단한 HTML 테이블을 기능이 풍부한 grid로 변환하는 매우 인기 있는 JavaScript 라이브러리입니다. jQuery는 AJAX 방식으로 MySQL에서 레코드를 가져오는 데 도움이 됩니다.
이 Datatable 자습서에서는 다음 기능을 다룹니다.
PHP 및 MySQL을 사용한 jQuery Ajax 데이터 테이블 목록
이 자습서에서는 레코드, 페이지 매김, 정렬 및 검색을 나열하는 Ajax 기반 DataTable을 구현하는 방법을 배웁니다.
그의 튜토리얼에 참여할 파일은 다음과 같습니다.
생성된 헤더 파일
/partials 폴더 아래에 header.php 파일을 만들고 이 파일에 아래 코드를 추가했습니다. 모든 css 및 js 파일을 header.php 파일에 포함합니다.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.0/css/dataTables.bootstrap5.min.css"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.11.0/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.11.0/js/dataTables.bootstrap5.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="js/common.js"></script>
이 튜토리얼의 뒷부분에서 common.js 파일을 만들 것입니다.
데이터 테이블 HTML 목록 생성
index.php 파일을 만들고 css 스타일로 HTML 테이블 요소를 추가했습니다. index.php 파일 상단에 header.php도 추가하겠습니다.
<?php
include('partials/header.php');
?>
<title>PHPFLOW.COM : Datatables Add Edit Delete with Ajax, PHP & MySQL</title>
<style>
.btn-group-xs>.btn,
.btn-xs {
padding: .25rem .4rem;
font-size: .875rem;
line-height: .5;
border-radius: .2rem;
}
</style>
</head>
<body class="">
<div class="container">
<h3>Ajax Datatables Listing With Sorting & Searching</h3>
<div class="col-lg-10 col-md-10 col-sm-9 col-xs-12">
<div class="panel-heading">
<div class="row">
<div class="col-md-10">
<button type="button" name="add" id="addEmployee" class="btn btn-success btn-xs"><i
class="bi bi-plus-circle-fill"></i> Add Employee</button>
</div>
<div class="col-md-2 pull-left">
</div>
</div>
</div>
<table id="dt-employee" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
작업 만들기
메서드 세부 정보로 모든 작업을 정의하고 아래 코드를 action.php 파일에 추가합니다.
<?php
include('Employee.php');
$emp = new Employee();
$action = isset($_POST['action']) && $_POST['action'] != '' ? $_POST['action'] : '';
switch ($action) {
case "listEmployee":
$emp->employeeList();
break;
default:
echo "Action not found!";
}
?>
AJAX 작업을 위한 자바스크립트 파일
js/ 폴더에 common.js 파일을 생성하겠습니다.
$(document).ready(function(){
var employeeData = $('#dt-employee').DataTable({
"lengthChange": false,
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"action.php",
type:"POST",
data:{action:'listEmployee'},
dataType:"json"
},
"columnDefs":[
{
"targets":[0, 2],
"orderable":false,
},
],
"pageLength": 10
});
});
dt-employee는 jquery 데이터 테이블 기능이 적용되는 html 테이블 ID입니다.
레코드 나열을 위한 작업 방법 정의
작업이 정의되었습니다. 이제 작업을 기반으로 모든 레코드를 가져오기 위해 Employee.php 파일에 코드 아래에 추가되었습니다.
public function employeeList(){
$where = $sqlTot = $sqlRec = "";
if( !empty($_POST['search']['value']) ) {
$where .=" WHERE ";
$where .=" ( employee_name LIKE '".$_POST['search']['value']."%' ";
$where .=" OR employee_salary LIKE '".$_POST['search']['value']."%' ";
$where .=" OR employee_age LIKE '".$_POST['search']['value']."%' )";
}
// getting total number records without any search
$sql = "SELECT * FROM ".$this->empTable." ";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
if(!empty($_POST["order"])){
$sqlRec .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
} else {
$sqlRec .= 'ORDER BY id DESC ';
}
if($_POST["length"] != -1){
$sqlRec .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$queryRecords = mysqli_query($this->dbConnect, $sqlRec);
$queryTot = mysqli_query($this->dbConnect, $sqlTot);
$numRows = mysqli_num_rows($queryTot);
$employeeData = array();
while( $employee = mysqli_fetch_assoc($queryRecords) ) {
$empRows = array();
$empRows[] = $employee['id'];
$empRows[] = ucfirst($employee['employee_name']);
$empRows[] = $employee['employee_age'];
$empRows[] = '<div class="btn-group" role="group" aria-label="Basic mixed styles example">
<button type="button" name="update" id="'.$employee["id"].'" class="btn btn-warning btn-xs update"><i class="bi bi-pencil-square"></i> Edit</button>
<button type="button" name="delete" id="'.$employee["id"].'" class="btn btn-danger btn-xs delete" ><i class="bi bi-trash"></i> Delete</button></div>';
$employeeData[] = $empRows;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $numRows,
"recordsFiltered" => $numRows,
"data" => $employeeData
);
echo json_encode($output);
}
결론:
MySQL에서 Ajax를 사용하여 Html 목록 데이터를 만들었습니다. 또한 해당 테이블에 데이터 테이블을 적용하여 기능이 풍부한 그리드를 생성합니다. 또한 입력된 사용자 검색 문자열을 기반으로 서버 측 정렬 및 검색 데이터를 추가했습니다. 모든 기능은 ajax 기반이므로 나열, 검색 및 정렬 시 페이지가 새로 고쳐지지 않습니다.
등록된 댓글이 없습니다.