Friday 29 March 2024

MySQL: How to Select Entire Row with MAX in Group By (Subquery Method)

 


Code : 

SELECT potential_customers.* from potential_customers where concat(potential_customers.customer_id,'-',potential_customers.next_call) IN

(SELECT concat(PC1.customer_id,'-',MAX(PC1.next_call)) FROM `potential_customers` PC1 GROUP by customer_id);

========================

Subscribe my Channel:-

http://www.youtube.com/user/SanketRooney?sub_confirmation=1


Gaming Channel:-

https://www.youtube.com/@unpoggaming9532


Gaming Instagram:- (@unpog.gaming)

https://www.instagram.com/unpog.gaming/

Facebook Page:-

https://www.facebook.com/UnpossibleNS

Twitter Account:-

https://twitter.com/UnpossiblePOG

Blog:-

https://unpossiblepog.blogspot.com/

Website:-

https://unpossiblepog.com/

========================

Hey guys, there is a limitation in MYSQL, where you use group by and wanted max value, but when you try to fetch a row ID or any other column, it fails.

For example, there is one table on the left side called “potential_customers”, and on the right side, I wrote one query which returns maximum NEXT_CALL value for each customer_id.

So, in current example I wanted row ID 2 & 6.

But if I need ID or whole row, it fails even when you use order by column_name DESC.

Thankfully there is a workaround for this which is to use the combination of subquery and concat.

First, let’s alter the query, to concat customer_id and max of next call. Remove all order by if there is any.

Put that query is sub-query by adding rounded brackets around it.

Now, write a select query before sub query, & in where condition, use concat of required column. Don’t forget to use “IN” keyword.

And as you can see, it returns row ID that we need.

You can call whole column if you want.

So that’s it. Code link is given in the description.

Thanks for watching. Like, Share and Subscribe.

Thursday 12 October 2023

Flutter | Create A Scrollable Pagination | Horizontal

 



Flutter | Create A Scrollable Pagination | Horizontal

-------------------------------

Link 1 Code (Data table) :-

https://unpossiblepog.blogspot.com/2023/10/Flutter-Datatable-With-Horizontal-Scroll-Display-Data-From-Rest-API.html

Note : Watch the video to understand how the code was made so that you can easily make changes as per your need.

Subscribe my Channel:-

http://www.youtube.com/user/SanketRooney?sub_confirmation=1

Gaming Channel:-

https://www.youtube.com/@unpoggaming9532

Gaming Instagram:- (@unpog.gaming)

https://www.instagram.com/unpog.gaming/

Facebook Page:-

https://www.facebook.com/UnpossibleNS

Twitter Account:-

https://twitter.com/UnpossiblePOG

Blog:-

https://unpossiblepog.blogspot.com/

Website:-

https://unpossiblepog.com/

========================

Important Note : Make sure to add “http: any” dependency in pubspec.yaml file.

main.dart code :

import 'package:flutter/material.dart';

import 'package:flutter/foundation.dart';

import 'package:http/http.dart' as http;

import 'dart:convert';

void main() {

runApp(const showListingPage());

}

List? dataList;

int totalPages = 0;

String filterListingString = "";

class showListingPage extends StatelessWidget {

const showListingPage({Key? key}) : super(key: key);

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'View All',

routes: {

},

theme: ThemeData(

primarySwatch: Colors.blue,

),

home: const ViewAllPage(title: 'View All'),

);

}

}

class ViewAllPage extends StatefulWidget {

const ViewAllPage({Key? key, required this.title}) : super(key: key);

final String title;

@override

State<ViewAllPage> createState() => _ViewAllPageStateViewAll();

}

class _ViewAllPageStateViewAll extends State<ViewAllPage> {

int total_records = 0;

List _posts = [];

int curr_page = 1;

int count_per_page = 2;

void loadDataFromAPI(int page_number,int per_page) async {

try {

final res =

await http.get(Uri.parse("http://unpossiblepog.com/apis/getFlutterPaginationApi.php?page="+page_number.toString()+"&per_page="+per_page.toString()));

setState(() {

_posts = json.decode(res.body);

if(_posts.length>0)

{

dataList = _posts;

total_records = int.parse(_posts[0]['count']);

totalPages =

(total_records / count_per_page).ceil();

}

});

} catch (err) {

if (kDebugMode) {

print('Something went wrong');

}

}

}

double numberFunction(int i)

{

int nun = i.toString().length;

String finalString = "0.";

for(int j=0;j<nun;j++)

{

finalString += "1";

}

finalString += "0";

return double.parse(finalString);

}

MaterialColor getColorForThis(int i)

{

MaterialColor c=Colors.green;

if(i==curr_page)

{

c=Colors.blue;

}

return c;

}

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: const Text('View All'),

centerTitle: true,

actions: <Widget>[],

),

body: ListView(children: <Widget>[

SingleChildScrollView(

padding: const EdgeInsets.all(8.0),

scrollDirection: Axis.horizontal,

child: DataTableOutputViewAll(),

),

SingleChildScrollView(

scrollDirection: Axis.horizontal,

child: Row(children: <Widget>[

SizedBox(

width: MediaQuery.of(context).size.width * 0.05,

),

//totalPages

for(var i=0;i<totalPages;i++) ...[

Container(

width: MediaQuery.of(context).size.width * numberFunction(i) * 1.5,

margin: const EdgeInsets.fromLTRB(0, 0, 10, 0),

height: 50.0,

child: RaisedButton(color: getColorForThis(i+1),

child: new Text(""+(i+1).toString(),style: TextStyle(color: Colors.white),),

onPressed: (){

curr_page = i+1;

loadDataFromAPI(i+1,count_per_page);

},

),

)

],

SizedBox(

width: MediaQuery.of(context).size.width * 0.05,

),

],),

)

]),

);

}

@override

void initState() {

super.initState();

dataList = null;

totalPages = 0;

if (dataList == null) {

loadDataFromAPI(1,count_per_page);

}

}

@override

void dispose() {

super.dispose();

}

}

class DataTableOutputViewAll extends StatelessWidget {

const DataTableOutputViewAll({Key? key}) : super(key: key);

List<InlineSpan> getData(Map<String, String> amount_entry_details) {

List<InlineSpan> temp = [];

amount_entry_details.forEach((k, v) => {

temp.add(

TextSpan(

style: const TextStyle(

color: Colors.black,

),

children: <TextSpan>[

TextSpan(

text: k + ' : ',

style: const TextStyle(fontWeight: FontWeight.bold)),

TextSpan(text: v + '\n'),

],

),

),

});

return temp;

}

@override

Widget build(BuildContext context) {

List<DataRow> rows = [];

if (dataList != null) {

for (int i = 0; i < dataList!.length; ++i) {

rows.add(DataRow(

cells: <DataCell>[

DataCell(Text(

'' + dataList![i]['language'].toString(),

style: TextStyle(fontSize: 15)),onTap: (){

}),

DataCell(

Text(

'' + dataList![i]['post_title'].toString(),

style: TextStyle(fontSize: 15)),onTap: (){

}),

],

));

}

}

return DataTable(

columns: const <DataColumn>[

DataColumn(

label: Text(

'Language',

style: TextStyle(fontStyle: FontStyle.italic),

),

numeric: false,

),

DataColumn(

label: Text(

'Title',

style: TextStyle(fontStyle: FontStyle.italic),

),

numeric: false,

),

],

rows: rows,

);

}

}

========================

Hey guys.

I have made a code which will generate a scrollable pagination feature in Flutter App. Today I am going to be sharing it’s code with you guys. Let’s get started.

The tutorial is divided into 2 phases.

1st is displaying data in data table.

2nd is adding scrollable pagination at bottom.

To execute the phase 1, what we shall do is a copy-paste from my blog. The link is given in the description with a title as “Link 1 Code (Data table)”

Instructions are given, we just have to follow it.

In new project, we shall add a dependency.

Make sure that it is at the same level as a flutter text.

Then, you can download that dependency using the command.

Copy-paste the whole code and paste it in main.dart file.

Let’s run the project.

You will see the data in data-table which itself is a scrollable.

The data is coming from the Rest API.

Each row is sending the total number of rows in count. Every API may send total row count in different key and at difference places or won’t send it at all so take a note to make sure it sends a total number of rows.

Lets begin a phase 2.

We already created a code to get total pages which will be shown at the bottom of an APP page.

Here, we will add another singlechildscrollview.

We will allow it to scroll horizontally.

Add a row as a child, advantage is that we can add multiple children in it which will be our pagination buttons.

The sizedbox is required, let me tell you why in a minute.

Let’s add a width in it.

Here you can see that the text ABC is appearing the right side of a screen.

We will do some mathematics to make it at the level of a data table.

Then I will be using a for loop.

Inside that will be our page buttons.

We will be using container with some specific width. This width will be dynamic, depending upon the length of a page number. I shall explain it in a minute.

For a button, we will be using a RaisedButton as a child.

Inside RaisedButton, we will temporarily add a 1 text.

OnPressed function is necessary.

Button appears.

We shall temporarily change the page count as 10 in for loop.

We will create a function called numberFunction which will be deciding the width of every button.

Let’s create that function which will return a double value.

Whenever the length of a page number changes, so will the float amount of that button.

Now the width looks OK.

Add i+1 as a text which will accurately display page number.

On pressed, we will change the current page number to highlight it.

Let’s make number’s color as white.

Because there are only 15 records, there are only 2 pages.

So let’s make 2 records per page.

We will add sizedBox at the end of container too to make some spacing from the right side.

To make some gap between buttons, we shall add margin as 10 from right side.

Set height property as 50.

To change content when clicked on button, call the loadDAtaFromAPI method on button’s onPressed function.

In pagination, there is always a feature will tells users the current page by highlighting it.

So let’s change the color of current page.

Because it is dynamic, we shall create another function called getColorForThis.

It will return a color by checking if that page number matches with current one.

There is some error.

So the return type should be MaterialColor.

Let’s run the project again.

You will see the pagination as expected. It is scrollable and go up to infinite.

There is a link in description called “Link 2 Code (Final Pagination)”. You can refer that if your code is not executing as expected.

Enjoy the code, play with it to create your own version.

Thanks for watching. Like, Share and Subscribe.

Saturday 7 October 2023

Flutter | Data-Table With Horizontal Scroll | Display Data From Rest API




1. Create a new project

-----------------------------

2. Add following line in dependencies (pubspec.yaml).

http: any

-----------------------------

3. Click on PUB GET button, or enter the command "flutter pub get" in terminal.

-----------------------------

4. Copy-paste the following code.


import 'package:flutter/material.dart';

import 'package:flutter/foundation.dart';

import 'package:http/http.dart' as http;

import 'dart:convert';

void main() {

  runApp(const showListingPage());

}

List? dataList;

int totalPages = 0;

String filterListingString = "";

class showListingPage extends StatelessWidget {

  const showListingPage({Key? key}) : super(key: key);

  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      title: 'View All',

      routes: {

      },

      theme: ThemeData(

        primarySwatch: Colors.blue,

      ),

      home: const ViewAllPage(title: 'View All'),

    );

  }

}

class ViewAllPage extends StatefulWidget {

  const ViewAllPage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override

  State<ViewAllPage> createState() => _ViewAllPageStateViewAll();

}

class _ViewAllPageStateViewAll extends State<ViewAllPage> {


  int total_records = 0;

  List _posts = [];

  int curr_page = 1;

  int count_per_page = 10;

  void loadDataFromAPI(int page_number,int per_page) async {

    try {

      final res =

      await http.get(Uri.parse("http://unpossiblepog.com/apis/getFlutterPaginationApi.php?page="+page_number.toString()+"&per_page="+per_page.toString()));

      setState(() {

        _posts = json.decode(res.body);

        if(_posts.length>0)

        {

          dataList = _posts;

          total_records = int.parse(_posts[0]['count']);

          totalPages =

              (total_records / count_per_page).ceil();

        }

      });

    } catch (err) {

      if (kDebugMode) {

        print('Something went wrong');

      }

    }

  }



  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: const Text('View All'),

        centerTitle: true,

        actions: <Widget>[],

      ),

      body: ListView(children: <Widget>[

        SingleChildScrollView(

          padding: const EdgeInsets.all(8.0),

          scrollDirection: Axis.horizontal,

          child: DataTableOutputViewAll(),

        ),

      ]), 

    );

  }

  @override

  void initState() {

    super.initState();

    dataList = null;

    totalPages = 0;

    if (dataList == null) {

      loadDataFromAPI(1,count_per_page);

    }

  }

  @override

  void dispose() {

    super.dispose();

  }


}

class DataTableOutputViewAll extends StatelessWidget {

  const DataTableOutputViewAll({Key? key}) : super(key: key);

  List<InlineSpan> getData(Map<String, String> amount_entry_details) {

    List<InlineSpan> temp = [];

    amount_entry_details.forEach((k, v) => {

      temp.add(

        TextSpan(

          style: const TextStyle(

            color: Colors.black,

          ),

          children: <TextSpan>[

            TextSpan(

                text: k + ' : ',

                style: const TextStyle(fontWeight: FontWeight.bold)),

            TextSpan(text: v + '\n'),

          ],

        ),

      ),

    });

    return temp;

  }

  @override

  Widget build(BuildContext context) {

    List<DataRow> rows = [];

    if (dataList != null) {

      for (int i = 0; i < dataList!.length; ++i) {

        rows.add(DataRow(

          cells: <DataCell>[

            DataCell(Text(

                '' + dataList![i]['language'].toString(),

                style: TextStyle(fontSize: 15)),onTap: (){

            }),

            DataCell(

                Text(

                    '' + dataList![i]['post_title'].toString(),

                    style: TextStyle(fontSize: 15)),onTap: (){

            }),

          ],

        ));

      }

    }

    return DataTable(

      columns: const <DataColumn>[

        DataColumn(

          label: Text(

            'Language',

            style: TextStyle(fontStyle: FontStyle.italic),

          ),

          numeric: false,

        ),

        DataColumn(

          label: Text(

            'Title',

            style: TextStyle(fontStyle: FontStyle.italic),

          ),

          numeric: false,

        ),

      ],

      rows: rows,

    );

  }

}


x

Thursday 27 July 2023

PHP Stock Contribution Logic | How To Split The Quantity In Sequence


 
PHP Contribution Logic | How To Split The Contribution In Sequence
-------------------------------

Code :

<?php
$friends = array("TONY STARK"=>500,"STEVE ROGERS"=>210,"NATASHA"=>290);
$foods = array("SHWARMA"=>450,"PIZZA"=>300,"BURGER"=>250);
echo "<pre>";print_r($friends);echo "</pre>";
echo "<pre>";print_r($foods);echo "</pre>";

while(sizeof($friends)>0)
{
$first_friend = array_key_first($friends);
$first_friend_amount = $friends[$first_friend];

//echo $first_friend." - ".$first_friend_amount;


$first_food = array_key_first($foods);
$first_food_amount = $foods[$first_food];

//echo $first_food." - ".$first_food_amount;
$final_amount = 0;
if($first_friend_amount<$first_food_amount)
{
$final_amount = $first_friend_amount;
}
else
{
$final_amount = $first_food_amount;
}

echo "<div>".$first_friend." - ".$first_food." - ".$final_amount."</div>";

$first_friend_amount = $first_friend_amount - $final_amount;
$friends[$first_friend] = $first_friend_amount;

$first_food_amount = $first_food_amount - $final_amount;
$foods[$first_food] = $first_food_amount;

if($friends[$first_friend]<=0)
{
unset($friends[$first_friend]);
}
if($foods[$first_food]<=0)
{
unset($foods[$first_food]);
}

//echo "<pre>";print_r($friends);echo "</pre>";
//echo "<pre>";print_r($foods);echo "</pre>";

//exit;
}
?>

-------------------------------

Copy The Code:-
Subscribe my Channel:-
http://www.youtube.com/user/SanketRooney?sub_confirmation=1
Facebook Page:-
https://www.facebook.com/UnpossibleNS
Twitter Account:-
https://twitter.com/UnpossiblePOG
Blog:-
https://unpossiblepog.blogspot.com/
Website:-
https://unpossiblepog.com/
Gaming Instagram:- (@unpog.gaming)
https://www.instagram.com/unpog.gaming/

========================
Hey guys, This is Unpossible POG.
Today I am going to demonstrate the contribution split logic using PHP language.
So suppose there are 2 arrays.
1st array represents people who contributes money for the food.
Their contribution’s total is 1000.
The 2nd array is the food’s amount in sequence.
So, the output we want is something like this.
Because TONY STARK spent 500, and Shawarma’s cost is 480, he actually paid full money for shwarama. And because of it 20 amount is left.
So it is adjusted to next food item which is PIZZA. Now PIZZA’s amount is reduced from 300 to 280.
Next is STEVE ROGERS, who spent all his money on PIZZA. And so on.
Here is the code.
We will be using a WHILE loop which is risky one if we don’t break it. So just add exit at the end which will be temporary.
Any ways, the logic is to find first elements from each array, in this case, a first person and first food.
I will be using some short-cuts to avoid typing.
Let’s print first elements.
We will create a variable which will hold the least amount of person or food. So let’s compare first amounts from both array.
Assign which one is the least to FINAL AMOUNT.
Let’s print.
Now, we have to deduct that FINAL AMOUNT from both array’s first amount.
And overwrite the first element’s amount from both arrays.
Let’s run to see the current situation.
SHWARMA’s amount is set to zero and TONY STARK’s amount is reduced down to 50.
If any PERSON AMOUNT or FOOD AMOUNT becomes zero after the subtraction, we will unset that element using UNSET function.
Now, arrays are overwritten.
Now we can remove exit from the bottom and see the result.
That’s it.
Code link is given in the description.
Thanks for watching. Like, Share and Subscribe.

Sunday 13 November 2022

Flutter Session Installation | Pros | Set & Get Functions | Remove Session Variable

 



========================
Note : newPage.dart file code is given below.
========================
1. In main.dart file, After int _counter = 0;
Add code given below
var sessionManager = SessionManager();
@override
void initState() {
super.initState();
setSessionValue();
}
setSessionValue()
async {
dynamic count = await SessionManager().get("count");
if(count!=null)
{
_counter=int.parse('$count');
_counter=_counter-1;
_incrementCounter();
}
}
----------------------------------
2.In main.dart file, at the end of _incrementCounter function
Add below line.
await sessionManager.set("count", _counter);
========================
newPage.dart File Code :
import 'package:flutter/material.dart';
import 'main.dart';
import 'package:flutter_session_manager/flutter_session_manager.dart';
class newPage extends StatelessWidget {
const newPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: const MyHomePage(title: 'Flutter Demo Page 2'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
var sessionManager = SessionManager();
@override
void initState() {
super.initState();
setSessionValue();
}
setSessionValue()
async {
dynamic count = await SessionManager().get("count");
if(count!=null)
{
_counter=int.parse('$count');
_counter=_counter-1;
_incrementCounter();
}
}
Future<void> _incrementCounter() async {
setState(() {
_counter++;
});
await sessionManager.set("count", _counter);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
children: <Widget>[
const Text(
'Second Page Count :',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
RaisedButton(
child: new Text('Jump To Previous Page'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyApp()),
);
},
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), 
);
}
}
-------------------------------
The biggest pros of using session in flutter or any other language is that you can pass values between 2 or multiple pages without form submission or setting it hidden field.
For example, there are 2 pages in flutter application, the PLUS button below increases the count on that page, I can set that value in session and pass it down in 2nd page and vice versa.
I shall show how to do the setup and how to implement session in flutter.
Let’s get started.
In basic project of flutter application, there is always a main.dart. file with a button which will increase the count. And I also added 2 raised-buttons manually in design to redirect to second page and to destroy session.
I also created another page called newPage.dart with some session code pre-applied, but it shows error because I haven’t added session library yet.
To add libraries or dependencies, pubspec.yaml file is used.
However, we are going add session library using commands.
So, let’s go to browser and search “flutter session”.
Click on installing tab.
There you will find command to install it in dependencies.
Run that command.
Reopen pubspec file, you will find flutter_session_manager line, which means the library is installed.
And there is no error in newPage.dart file.
Let’s go to main.dart file.
I shall enable code to redirect to second page.
To make session library actually work in dart file, we have to import it.
If we go to Readme tab, you will find session code, like how to create session variable.
I shall use 1st and 3rd line.
Actually I created some code. So just copy-paste it. Code link is given in the description.
From 1st point, copy the code and paste it below _counter variable.
This code is used for fetching session variable at the page-start.
SessionManager.get function is used for it.
To set the session variable “count”, sessionManager.set function is used.
Use it after the setState function.
Let’s run the project.
Let’s test the code.
From first page, I shall set counter value to 4.
And that value is successfully called in 2nd page.
From this page, if I change it, it will be reflected in 1st page.
We can also destroy session by using destroy function.
Or we can unset it.
So, in second raised-button, I shall call remove function.
That’s it.
Thanks for watching. Like, Share and Subscribe.

Tuesday 30 August 2022

Data Table & Jquery | Overwrite The Count Of Result

 


Data Table & Jquery | Overwrite The Count Of Result

-------------------------------

Subscribe my Channel:-

http://www.youtube.com/user/SanketRooney?sub_confirmation=1

Facebook Page:-

https://www.facebook.com/UnpossibleNS

Twitter Account:-

https://twitter.com/UnpossiblePOG

Blog:-

https://unpossiblepog.blogspot.com/

Website:-

https://unpossiblepog.com/

Gaming Instagram:- (@unpog.gaming)

https://www.instagram.com/unpog.gaming/

-------------------------------

Code :-

<table id="userTable">

<thead>

<th>First Name</th>

<th>Last Name</th>

<th>Age</th>

</thead>

<tbody>

<tr>

<td>Extra Column 1</td>

<td>Extra Column 2</td>

<td>Extra Column 3</td>

</tr>

<tr>

<td>100</td>

<td>Steven</td>

<td>King</td>

</tr>

<tr>

<td>101</td>

<td>Neena</td>

<td>Kochhar</td>

</tr>

<tr>

<td>102</td>

<td>Lex</td>

<td>De Haan</td>

</tr>

<tr>

<td>103</td>

<td>Alexander</td>

<td>Hunold</td>

</tr>

<tr>

<td>104</td>

<td>Bruce</td>

<td>Ernst</td>

</tr>

<tr>

<td>105</td>

<td>David</td>

<td>Austin</td>

</tr>

<tr>

<td>106</td>

<td>Valli</td>

<td>Pataballa</td>

</tr>

<tr>

<td>107</td>

<td>Diana</td>

<td>Lorentz</td>

</tr>

<tr>

<td>108</td>

<td>Nancy</td>

<td>Greenberg</td>

</tr>

<tr>

<td>109</td>

<td>Daniel</td>

<td>Faviet</td>

</tr>

<tr>

<td>110</td>

<td>John</td>

<td>Chen</td>

</tr>

<tr>

<td>111</td>

<td>Ismael</td>

<td>Sciarra</td>

</tr>

<tr>

<td>112</td>

<td>Jose Manuel</td>

<td>Urman</td>

</tr>

<tr>

<td>113</td>

<td>Luis</td>

<td>Popp</td>

</tr>

<tr>

<td>114</td>

<td>Den</td>

<td>Raphaely</td>

</tr>

<tr>

<td>115</td>

<td>Alexander</td>

<td>Khoo</td>

</tr>

<tr>

<td>116</td>

<td>Shelli</td>

<td>Baida</td>

</tr>

<tr>

<td>117</td>

<td>Sigal</td>

<td>Tobias</td>

</tr>

<tr>

<td>118</td>

<td>Guy</td>

<td>Himuro</td>

</tr>

<tr>

<td>119</td>

<td>Karen</td>

<td>Colmenares</td>

</tr>

</tbody>

</table>

<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script type="text/javascript" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>

<script>

$(document).ready(function() {

$('#userTable').DataTable({

"ordering": false,

"searching":false,

initComplete: function() {

pageCountDatatable();

}

});

});

function pageCountDatatable()

{

var actual_cnt=20;

var str_array = $("#userTable_info").html().split(" ");

for(var i=0;i<str_array.length;i++)

{

if(!isNaN(str_array[i]))

{

if(parseInt(str_array[i])>actual_cnt)

{

str_array[i] = actual_cnt;

}

}

}

$("#userTable_info").html(str_array.join(" "));

$("#userTable_info").show();

}

$("#userTable").on('page.dt',function(){

$("#userTable_info").hide();

setTimeout(function(){

pageCountDatatable();

},1000);

});

$("#userTable").on('length.dt',function(){

$("#userTable_info").hide();

setTimeout(function(){

pageCountDatatable();

},1000);

});

</script>

-------------------------------

In this tutorial, I shall show how we can overwrite the count of result in data table.

Here, we have one data table with 20 rows of actual data.

In this data table, I just wanted to add extra row which will represent additional column and will not be the part of the actual data.

So, actually I wanted to display 20 entries as a text instead of 21 entries.

So for that, I shall create a javascript function.

I am going to call it inside initComplete function.

For now, we add static value of actual row count as 20 rows.

Of course you can get that count dynamically.

Just inspect element, and find out the ID for that div.

Copy it.

We shall use it’s ID to get text inside it.

We shall split it by space. And convert it into an array.

In for loop, first we shall find out whether the specific array position has numeric value to it or not because we don’t want to replace texts. Then, we shall only replace numbers and those numbers which are greater than 20.

After the end of the loop, we shall overwrite the text in same ID.

So, if we refresh, we shall see that it is showing “20 entries” text.

However if we change the length per page, or change pages, it will again go back to “21 entries” text.

So for that, first copy the table ID, on its page change event, we shall write some jquery.

If we change page number, it shows an alert box, but it won’t change the text even if we call function.

So to fix that, we have to delay it’s execution by using the setTimeout function.

The time delay will be 1 second.

Call our function inside it.

However the output behaves weirdly so we shall hide it the page changes.

And we shall show it when the output becomes ready.

To display same output when page length is changed, copy-paste the whole code.

And replace “page” with “length”.

And now, your output will display no more than 20 entries text.

You can copy-paste the code from the link given in the description.

Thanks for watching. Like, Share and Subscribe.