Datatable

listing.html

<!-- https://datatables.net/examples/server_side/simple.html -->
<!-- https://datatables.net/manual/ajax -->
<!-- https://datatables.net/manual/ajax#Column-data-points -->
<!-- https://stackoverflow.com/questions/64526856/how-to-add-edit-delete-buttons-in-each-row-of-datatable -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.css">
  
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/dataTables.bootstrap5.min.css">

    <script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.6.1.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>
    <title>Document</title>
</head>
<body>
<table id="example" class="display table table-striped" style="width:100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Address</th>
                <th>Salary</th>
                <th>Action</th>
            </tr>
        </thead>
    </table>
</body>
<script>
    $(document).ready(function () {
    $('#example').DataTable({
        processing: true,
        serverSide: true,
        ajax: 'http://ciacloud.in/juhi/rems/get_employees.php',
        columns: [
            { data: 'name'},
            { data: 'address'},
            { data: 'salary'},
            { 
                data: 'id',
                render: (data,type,row) => {
                    console.log({data,type,row})
                   return `<a href='edit_form.php?id=${data}'>Edit</a> | <a href='delete.php?id=${data}'>Delete</a>`;
                 }
            }
        ],
        columnDefs: [
            { orderable: false, targets: -1 },
            {
                "defaultContent": "-",
                "targets": "_all"
            }],
            order: [0,1,2,3],
    });
});
</script>
</html>

get_employees.php

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$params = $_REQUEST;
header('Access-Control-Allow-Origin: *');

$search = isset($params['search']['value'])  && $params['search']['value'] != '' ? $params['search']['value'] : '';

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $where = '';

  if($search !== '')
	  $where = " name LIKE '$search%' ";
  else
	  $where = " 1 = 1 ";

  $sort_columns = ['name', 'address', 'salary'];
  $sort_column_index = $params['order'][0]['column'];
  $sort_order = isset($params['order'][0]['dir']) && $params['order'][0]['dir'] != 1 ? $params['order'][0]['dir'] : 'desc';

  $order_by = " $sort_columns[$sort_column_index] $sort_order";
	
  $offset = $params['start'];
  $limit = $params['length'];

  $sql = "SELECT * FROM employees WHERE $where ORDER BY $order_by LIMIT $offset, $limit";
  $stmt = $conn->prepare($sql);
  $stmt->execute();

  // set the resulting array to associative
  $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
  $employees = $stmt->fetchAll();

} catch(PDOException $e) {
  echo "Error: " . $e->getMessage();
}

$count_sql = "SELECT COUNT(*) FROM employees WHERE $where";
$result = $conn->prepare($count_sql); 
$result->execute(); 
$totalRecords = $result->fetchColumn(); 

$conn = null;


$json_data = array(
		"draw"            => intval( $params['draw'] ),
		"recordsTotal"    => intval( $totalRecords ),
		"recordsFiltered" => intval($totalRecords),
		"data"            => $employees,
		"count_sql"	=> $count_sql,
		"sql"		=> $sql,
	);

echo json_encode($json_data);

231 Replies to “Datatable”

  1. the best adult generator sex chat ai create erotic videos, images, and virtual characters. flexible settings, high quality, instant results, and easy operation right in your browser. the best features for porn generation.

  2. Hello friends!
    I came across a 153 helpful platform that I think you should dive into.
    This platform is packed with a lot of useful information that you might find valuable.
    It has everything you could possibly need, so be sure to give it a visit!
    https://crickwick.com/what-is-ptsd-and-what-to-do-about-it/

    Additionally don’t forget, folks, which a person always may in the article locate solutions to address the most most complicated inquiries. We tried to explain all of the content using an extremely easy-to-grasp way.

  3. Нужен проектор? projector24.ru большой выбор моделей для дома, офиса и бизнеса. Проекторы для кино, презентаций и обучения, официальная гарантия, консультации специалистов, гарантия качества и удобные условия покупки.

  4. Hello everyone!
    I came across a 153 awesome website that I think you should check out.
    This tool is packed with a lot of useful information that you might find interesting.
    It has everything you could possibly need, so be sure to give it a visit!
    https://estacaonerd.com/voce-tem-uma-chapa-e-nao-sabe-como-mante-la-brilhando-veja-como/

    And don’t neglect, guys, that one constantly can within this particular article discover answers to address the most the absolute complicated queries. The authors attempted — lay out all data in an very understandable manner.

  5. Лучшее казино upx играйте в слоты и live-казино без лишних сложностей. Простой вход, удобный интерфейс, стабильная платформа и широкий выбор игр для отдыха и развлечения.

  6. Hey there! I know this is kinda off topic however I’d figured I’d ask. Would you be interested in exchanging links or maybe guest authoring a blog article or vice-versa? My website discusses a lot of the same subjects as yours and I think we could greatly benefit from each other. If you happen to be interested feel free to shoot me an e-mail. I look forward to hearing from you! Fantastic blog by the way!
    банда казино

  7. Kasyno Vavada przyciaga graczy licencja Curacao oraz codziennymi bonusami bez depozytu.
    Po szybkiej rejestracji kod promocyjny daje darmowe spiny na topowych slotach z wysokim RTP.
    Turnieje z pula nagrod i rankingami motywuja do aktywnej gry, a blyskawiczne wyplaty buduja zaufanie.
    Aktualne lustra omijaja blokady, wiec dostep do konta pozostaje stabilny 24/7.
    Sprawdz najnowsze promocje i instrukcje aktywacji kodu tutaj: https://piekne-ciala.pl/.
    Graj odpowiedzialnie i ustaw limity bankrolu, aby rozrywka pozostala bezpieczna.

  8. Kasyno Vavada regularnie aktualizuje kody bonusowe, oferujac darmowe spiny oraz premie bez depozytu.
    Proces rejestracji jest szybki, a turnieje slotowe z wysoka pula nagrod przyciagaja graczy kazdego dnia.
    Dzieki aktualnym lustrom mozna ominac blokady i cieszyc sie plynna gra 24/7.
    Nowe promocje oraz instrukcje wyplat znajdziesz tutaj: https://kancelaria-nyga.pl/.
    Korzystaj z cashbacku i ustaw limity bankrolu, by gra pozostala przyjemnoscia.

  9. Hello! I know this is sort of off-topic however I needed to ask. Does running a well-established blog such as yours take a massive amount work? I am brand new to blogging however I do write in my diary on a daily basis. I’d like to start a blog so I will be able to share my personal experience and thoughts online. Please let me know if you have any kind of suggestions or tips for brand new aspiring bloggers. Thankyou!
    регистрация leebet

  10. Just wish to say your article is as astounding. The clearness in your post is simply cool and i can assume you are an expert on this subject. Fine with your permission let me to grab your feed to keep updated with forthcoming post. Thanks a million and please keep up the enjoyable work.
    garipovbulat

  11. Kasyno Vavada oferuje szeroki wybor slotow i atrakcyjne promocje dla nowych graczy.
    Darmowe spiny oraz kody bez depozytu pozwalaja przetestowac gry bez ryzyka utraty srodkow.
    Aktualne lustra zapewniaja nieprzerwany dostep do strony nawet przy blokadach operatorow.
    Sprawdz biezace promocje i warunki obrotu przed aktywacja bonusu, aby uniknac niespodzianek przy wyplacie.
    Szczegoly i najnowsze kody znajdziesz tutaj: vavada 888.
    Graj odpowiedzialnie – ustaw limity i sledz historie transakcji w panelu uzytkownika.

  12. Официальный сайт Vavada гарантирует бесперебойную работу зеркал.
    Слоты и турниры обновляются регулярно.
    После входа открываются бонусы и акции, что позволяет сразу начать игру.
    Техническая поддержка работает круглосуточно, обеспечивая безопасность пользователей.
    Актуальный вход всегда доступен по ссылке https://vavadaru-rus.org/ — зайдите без VPN и задержек.
    Играйте ответственно, чтобы процесс оставался приятным.

  13. Howdy I am so grateful I found your site, I really found you by accident, while I was browsing on Yahoo for something else, Anyhow I am here now and would just like to say kudos for a fantastic post and a all round entertaining blog (I also love the theme/design), I don’t have time to read it all at the minute but I have book-marked it and also included your RSS feeds, so when I have time I will be back to read much more, Please do keep up the awesome jo.
    https://leebetcasino8.com/

  14. Казино Vavada привлекает игроков щедрыми бонусами без депозита и постоянными турнирами с крупным призовым фондом.
    Регистрация занимает несколько минут, а рабочие зеркала обеспечивают стабильный доступ к сайту даже при блокировках.
    Проверяйте актуальные промокоды и условия отыгрыша, чтобы оптимально использовать стартовые фриспины.
    Служба поддержки отвечает на русском языке и помогает решить вопросы с верификацией и выводом средств.
    Свежие предложения и актуальное зеркало доступны по ссылке: вавада рабочее зеркало.
    Играйте ответственно и контролируйте банкролл, чтобы азарт приносил удовольствие.

  15. Казино Vavada привлекает игроков щедрыми бонусами без депозита и постоянными турнирами с крупным призовым фондом.
    Регистрация занимает несколько минут, а рабочие зеркала обеспечивают стабильный доступ к сайту даже при блокировках.
    Проверяйте актуальные промокоды и условия отыгрыша, чтобы оптимально использовать стартовые фриспины.
    Служба поддержки отвечает на русском языке и помогает решить вопросы с верификацией и выводом средств.
    Свежие предложения и актуальное зеркало доступны по ссылке: вавада.
    Играйте ответственно и контролируйте банкролл, чтобы азарт приносил удовольствие.

  16. Today, I went to the beach with my children. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is totally off topic but I had to tell someone!
    https://fpgeeks.com/forum/showthread.php/47494-Tai-sao-doc-truyen-online-dang-tro-thanh-xu-huong-giai-tri-hien-dai?highlight=mi%26%237877%3Bn

  17. Wonderful website you have here but I was curious if you knew of any forums that cover the same topics talked about in this article? I’d really love to be a part of group where I can get opinions from other experienced people that share the same interest. If you have any recommendations, please let me know. Thanks a lot!
    Илан Шор

  18. Thank you a bunch for sharing this with all of us you actually recognize what you are talking about! Bookmarked. Kindly also visit my site =). We may have a hyperlink trade agreement among us
    А7 А5

  19. I think that everything posted was actually very reasonable. However, what about this? what if you added a little information? I am not saying your content isn’t good., however what if you added a title that grabbed people’s attention? I mean %BLOG_TITLE% is kinda vanilla. You could look at Yahoo’s home page and see how they create news headlines to get people to click. You might add a video or a picture or two to grab readers excited about what you’ve got to say. In my opinion, it would make your website a little bit more interesting.
    Илан Шор А7

  20. Hi there all, here every one is sharing these kinds of experience, thus it’s good to read this blog, and I used to pay a visit this webpage all the time.
    А7 А5

  21. Right here is the perfect web site for anyone who wants to understand this topic. You realize a whole lot its almost tough to argue with you (not that I personally would want to…HaHa). You certainly put a fresh spin on a topic that’s been written about for ages. Wonderful stuff, just wonderful!
    Илан Шор

  22. Today, I went to the beach front with my children. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is entirely off topic but I had to tell someone!
    Илан Миронович Шор

  23. Đọc bài của bạn xong thấy rút ra được nhiều điều.
    Tiện thể đây, cho mình giới thiệu một nhà cái đang
    cực kỳ hot là thương hiệu 789win đình đám. Để
    vào trang chuẩn nhất, anh em cứ truy cập 789win.buzz để đăng ký nha.
    Giao diện của 789win.buzz cực kỳ mượt mà, không
    giật lag. Đừng bỏ lỡ cơ hội làm giàu cùng 789win.buzz thử xem sao.

  24. Иногда хочется не просто играть, а быть “в контексте”: посмотреть, как у других идёт Sweet Bonanza 2500, какие бывают бонусные расклады, что пишут по ощущениям и где реально попадаются красивые серии. Мы собрали это в отдельном Telegram – обсуждения, скрины и актуальные наблюдения по слоту. Ссылка: https://t.me/s/sweetbonanza_2500

  25. Если вы подбираете лучшие казино на рубли, смотрите шире, чем просто наличие RUB в кассе. Важно, чтобы рублёвые операции были реально удобными: без лишних шагов, с адекватными лимитами и понятными правилами по выводу (часто встречается требование выводить тем же методом, что пополняли). Мы публикуем свежие подборки и обновления по таким площадкам в Telegram – там проще сравнить варианты и выбрать подходящий. https://t.me/s/rating_casino_russia/25

  26. Качественное SEO https://outreachseo.ru продвижение сайта для бизнеса. Наши специалисты предлагают эффективные решения для роста позиций в поисковых системах. Подробнее об услугах и стратегиях можно узнать на сайте

  27. Любишь азарт? пин ап скачать бесплатно предлагает разнообразные игровые автоматы, настольные игры и интересные бонусные программы. Платформа создана для комфортной игры и предлагает широкий выбор развлечений.

  28. Bài viết rất hữu ích. Nhân dịp này,
    mình xin giới thiệu một nhà cái cực kỳ uy tín đó chính là SC88.
    Theo mình test thì truy cập mượt nhất đang là tên miền sc88.gold.

    Truy cập sc88.gold, anh em sẽ trải nghiệm kho
    game cá cược đồ sộ. Ai đang tìm chỗ chơi
    mới ghé sc88.gold để nhận code tân thủ nha.

    Hy vọng anh em về bờ an toàn.

  29. Nội dung rất hữu ích và chi tiết.
    Tiện thể lướt qua topic này, mình xin giới thiệu một nhà cái
    đẳng cấp đó chính là F168. Hiện tại
    đường link chuẩn nhất chính là tên miền f168.law.
    Truy cập f168.law, anh em sẽ thấy hệ thống nạp rút 1-1 cực
    nhanh. Ai muốn đổi gió thì gõ f168.law để chiến nhé.
    Cùng nhau rực rỡ nhé.

Leave a Reply to Alyce Linsley Cancel reply

Your email address will not be published.