Sorting Integer in MySQL-PHP - php

I have a webpage http://skywateryachts.com/disp_new.php where I formatted the currency with no problem.
However, the sorting of the listed price appears to be by order of the first several digits rather than total value. Example, $110,000 appears before $110,900,000 when sorted descending.
The MySQL field type is INT and I just formatted the SELECT statement for the currency symbol.
I'm using the dataviewer extension in the WYSISWYG Webbuilder and custom formatting the code. But I am new to customizing MySQL.
I'm thinking it would be better to eliminate the sort feature and do it myself but would like first to know what the issue could be with the sorting of the digits.
Thanks
Pertinent code:
<script type="text/javascript">
$(document).ready(function()
{
$.fn.alternateRowColors = function()
{
$('tbody tr:odd', this).removeClass('even').addClass('odd');
$('tbody tr:even', this).removeClass('odd').addClass('even');
return this;
};
$('table.sortable').each(function()
{
var $dataviewer = $(this);
$dataviewer.alternateRowColors();
$('th', $dataviewer).each(function(column)
{
var $header = $(this);
var findSortKey;
findSortKey = function($cell)
{
return $cell.find('.sort-key').text().toUpperCase() + ' ' + $cell.text().toUpperCase();
};
if (findSortKey)
{
$header.addClass('clickable').hover(function()
{
$header.addClass('hover');
}, function()
{
$header.removeClass('hover');
}).click(function()
{
var sortDirection = 1;
if ($header.is('.sorted-asc'))
{
sortDirection = -1;
}
var rows = $dataviewer.find('tbody > tr').get();
$.each(rows, function(index, row)
{
var $cell = $(row).children('td').eq(column);
row.sortKey = findSortKey($cell);
});
rows.sort(function(a, b)
{
if (a.sortKey < b.sortKey) return -sortDirection;
if (a.sortKey > b.sortKey) return sortDirection;
return 0;
});
$.each(rows, function(index, row)
{
$dataviewer.children('tbody').append(row);
row.sortKey = null;
});
$dataviewer.find('th').removeClass('sorted-asc').removeClass('sorted-desc');
if (sortDirection == 1)
{
$header.addClass('sorted-asc');
}
else
{
$header.addClass('sorted-desc');
}
$dataviewer.find('td').removeClass('sorted').filter(':nth-child(' + (column + 1) + ')').addClass('sorted');
$dataviewer.alternateRowColors();
});
}
});
});
<div id="dataviewer" style="position:absolute;overflow:auto;left:269px;top:390px;width:803px;height:980px;z-index:46">
<?php
$mysql_host = 'localhost';
$mysql_user = 'xxxx';
$mysql_password = 'xxxx';
$mysql_database = 'xxxx';
$mysql_table = 'boats';
$db = mysql_connect($mysql_host, $mysql_user, $mysql_password);
mysql_select_db($mysql_database, $db);
$sql = "SELECT Date_Listed, Est_DOM, LOA, Builder, Built, Currency, concat('$', format(Listing_Price, 0)), NFS_USA FROM ".$mysql_table;
$result = mysql_query($sql, $db);
?>
<table cellpadding="0" cellspacing="1" width="100%" class="sortable paginated">
<thead>
<tr>
<th>List Date</th>
<th> Est DOM</th>
<th> Length</th>
<th> Builder</th>
<th> Year Built</th>
<th> Currency</th>
<th> Listing Price</th>
<th> NFS USA</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysql_fetch_row($result))
{
echo " <tr>\n";
foreach ($row as $cell)
{
echo " <td>" . $cell . "</td>\n";
}
echo " </tr>\n";
}
?>
</tbody>
</table>
</div>

You probably are sorting by your formatted column in the field list of your SELECT. Instead, in your ORDER BY reference the name of the integer column directly from your table.
So if you have this:
SELECT FORMAT(foo, '$99,999,999.99')
FROM bar
ORDER BY 1
instead do this
SELECT FORMAT(foo, '$99,999,999.99')
FROM bar
ORDER BY foo
(Ignore the actual syntax of the formatting - I always have to look that stuff up to get the right function and syntax and I'm just doing it for an example.)

Related

Showing a sql table when radio button is selected using AJAX

I have a webpage with three radio buttons and an empty table. My goal is to select a radio button and have the table show a list of employees based on whichever radio button is clicked. Right now the list does not show up when I hit the button. I don't know what I'm doing wrong. I tried adding an alert to the doAjax function and the alert appeared so I know it's getting to that function. Below is my code, I have three files. Any help is appreciated.
//assign3.php
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src = "http://code.jquery.com/jquery-3.2.1.min.js">
</script>
<script src ="js/assign3js.js" type = "text/javascript" ></script>
</head>
<body>
<table border ='1'style = 'margin:auto' id = "employees" >
<tr><td colspan ='3'><h1>Employees </h1></td></tr>
<th> First Name</th>
<th>Last Name</th>
<th>Employee ID</th>
</table>
<input type="radio" name="employeeType" value="server" id="server"> Server<br>
<input type="radio" name="employeeType" value="bartender"id="bartender"> Bartender<br>
<input type="radio" name="employeeType" value="host"id = "hosts"> Host<br>
</body>
//script.js
$("document").ready(
function()
{
$("#server").click(doAjax);
$("#hosts").click(doAjax1);
$("#bartender").click(doAjax2);
}
);
function doAjax()
{
$.ajax({"method":"POST","url":"servers.php"}).done(update);
}
function update(data)
{
result = JSON.parse(data);
for(index =0; index < result.length; index++)
{
var row = "<tr>";
row += "<td>" + result[index].firstName + "</td>";
row += "<td>" + result[index].lastName + "</td>";
row += "<td>" + result[index].employeeID + "</td>";
row += "</tr>";
$("#employees").append(row);
}
}
//server.php
<?php
$server = (object) null;
$connection = "mysql:host=localhost;dbname=restaurant";
$user = "root";
$pwd = "mysql";
$db = new PDO($connection, $user, $pwd);
$results = $db->query("SELECT firstName, lastName, employeeID FROM
employee JOIN `server` ON employee.employeeID = server.employeeID");
while ($row = $results->fetch())
{
$server->firstName= $row["firstName"];
$server-> lastName=$row["lastName"] ;
$server->employeeId = $row["employeeID"];
}
$employee = [];
array_push($employee,$server);
$json1 = json_encode($employee);
echo $json1;
?>
My answer is just an addition to #alex's answer. Alex has very good pointed out the main problems/aspects!
I would suggest you another approach: to use only one js function for getting the employee data, no matter which radio button you are selecting. When you click on a radio button, send an ajax request with the corresponding radio button's value as argument. This value will be read on the server side and, dependent on it, a corresponding sql statement will be built and executed. The response will be read and appended to the employees table.
There would be too much to say here regarding your code version and my proposal. I hope you'll understand what I did.
Main points:
I renamed "server.php" to "get-employee.php" (it's obvious why).
I implemented the use of prepared statements instead of query, so that you are on a safe side in regard of the sql injection, in case you need to use input parameters in your queries.
The employee data is fetched from db and saved in an array by using the fetchAll() method. No need for fetching and looping through objects.
The db connection details are defined in constants.
An array with db connection options regarding exception handling and others is added now (needed).
Added the tbody container to the table, to which the employees data will be appended. In general, if you use th then use it inside a thead container. And if you use thead, then use a tbody too.
I think this is all that's important. Feel free to ask me anything... tomorrow.
Good luck further.
assign3js.js
$(document).ready(function () {
$('input[name="employeeType"]').click(function () {
var employeeType = $(this).val();
updateEmployees(employeeType);
});
});
function updateEmployees(type) {
$.ajax({
method: 'post',
dataType: 'json',
url: 'get-employee.php',
data: {
'type': type
}
})
.done(function (response, textStatus, jqXHR) {
if (response) {
for (var i = 0; i < response.length; i++) {
var row = '<tr>';
row += '<td>' + response[i].firstName + '</td>';
row += '<td>' + response[i].lastName + '</td>';
row += '<td>' + response[i].employeeID + '</td>';
row += '</tr>';
$('#employees tbody').append(row);
}
} else {
$('#employees tbody').append('<tr><td colspan="3">No employees found</td></tr>');
}
})
.fail(function (jqXHR, textStatus, errorThrown) {
// alert(textStatus + '\n' + errorThrown + '\n\n' + jqXHR.responseText);
})
.always(function (response, textStatus, jqXHR) {
//...
});
}
assign3.php:
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="js/assign3js.js" type="text/javascript"></script>
<style type="text/css">
#employees {
/*margin: auto;*/
border: 1px solid #ccc;
}
#employee-types {
margin-top: 20px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<table id="employees">
<thead>
<tr>
<th colspan="3">
<h1>Employees</h1>
</th>
</tr>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Employee ID</th>
</tr>
</thead>
<tbody></tbody>
</table>
<fieldset id="employee-types">
<legend>Employee type</legend>
<input type="radio" id="server" name="employeeType" value="server">
<label for="server">Server</label><br/>
<input type="radio" id="bartender" name="employeeType" value="bartender">
<label for="bartender">Bartender</label><br/>
<input type="radio" id="hosts" name="employeeType" value="host">
<label for="hosts">Host</label><br/>
</fieldset>
</body>
</html>
get-employee.php
<?php
// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'restaurant');
define('USERNAME', 'root');
define('PASSWORD', 'mysql');
define('CHARSET', 'utf8');
// Error reporting.
error_reporting(E_ALL);
ini_set('display_errors', 1); // SET IT TO 0 ON A LIVE SERVER!
//
// Create a PDO instance as db connection to db.
$connection = new PDO(
sprintf('mysql:host=%s;port=%s;dbname=%s;charset=%s', HOST, PORT, DATABASE, CHARSET)
, USERNAME
, PASSWORD
, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);
$response = false;
if (isset($_POST['type'])) {
$employeeType = $_POST['type'];
/*
* The bindings array, mapping the named markers from the sql statement
* (if any) to the corresponding values. It will be directly passed as
* argument to the PDOStatement::execute method.
*
* #link http://php.net/manual/en/pdostatement.execute.php
*/
$bindings = [];
// Set the sql statement based on the submitted employee type.
switch ($employeeType) {
case 'bartender':
// $sql = '...';
// $bindings[:markerName] = markerValue;
break;
case 'hosts':
// $sql = '...';
// $bindings[:markerName] = markerValue;
break;
case 'server':
default:
$sql = 'SELECT
emp.firstName,
emp.lastName,
emp.employeeID
FROM employee AS emp
JOIN `server` AS srv ON srv.employeeID = emp.employeeID';
break;
}
// Prepare the sql statement for execution and return a statement object.
$statement = $connection->prepare($sql);
// Execute the prepared statement.
$statement->execute($bindings);
// Fetch data - all at once - and save it into response array.
$response = $statement->fetchAll(PDO::FETCH_ASSOC);
//-----------------------------------------------------------------------
// ...or fetch data one record at a time and save it into response array.
//-----------------------------------------------------------------------
// $employee = [];
// while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
// $employee[] = $row;
// }
// $response = $employee;
//-----------------------------------------------------------------------
}
echo json_encode($response);
Your SQL query is wrong, you have it doing
SELECT firstName, lastName, employeeID FROM employee JOIN `server` ON
employee.employeeID = server.employeeID
but employeeID exists in both employee and server so you need to modify your query to specific which table to get employeeID from so it should look like
SELECT employee.firstName, employee.lastName, employee.employeeID FROM employee JOIN `server` ON
employee.employeeID = server.employeeID
I made an SQLFiddle here which shows this. You should check if $results equals false, because the query function will return false if it fails.
That worked for me, I had to change line 14 in server.php as well or else it wouldn't display the employee ID, this was because in the ajax script you reference it as employeeID but you set it as employeeId on line 14 so it would now be
$server->employeeID = $row["employeeID"];
Now when you run all of it will only one employee, if you want it to return multiple you need to have an array in server.php that you push employees to because right now it will overwrite the previous employee and only return the last one because of them writing to the same object with the same keys.
For multiple employees to return I changed the code to
...
$server = [];
...
$count = 0;
while ($row = $results->fetch()) {
//create new class to stop warnings of creating object from empty value
$server[$count] = new \stdClass();
$server[$count]->firstName= $row["firstName"];
$server[$count]->lastName=$row["lastName"] ;
$server[$count]->employeeID = $row["employeeID"];
$count++;
}
...
what this does is $server is now an array, and every time we loop over an employee in the while loop we assign our values to a new object stored in $server's array.
and the script.js looked like this
function update(data) {
var result = JSON.parse(data)[0]; // [0] because the json was wrapped in
// double []'s
for(var index =0; index < result.length; index++) {
var row = "<tr>";
row += "<td>" + result[index].firstName + "</td>";
row += "<td>" + result[index].lastName + "</td>";
row += "<td>" + result[index].employeeID + "</td>";
row += "</tr>";
$("#employees").append(row);
}
}
Not sure if any of this is the best solution to the problem, but I got it to work without too much trouble.

Progress Bar with Ajax JQuery and PHP for import a .csv file to MySQL

I tried to write a code for a progress bar using PHP, JQuery and HTML.
So, I made a Ajax Request for a PHP file and in the success Ajax parameter I search a data requested from PHP File like this..
success: function(data){
if(data == 'Error1'){
alert("The File is not a .csv");
}else if(data == "Error2"){
alert("Please select a file to import!");
}else{
$('#consumidor_table').html(data);
alert("The importation has been made!");
}
}
That else does print a Table with MySql DB lines. The PHP file read a .csv from a HTML input and insert those lines in DB.
Actually, my code to do a progress bar is it:
Before at success parameter
xhr: function(){
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log(evt.loaded);
console.log(evt.total);
console.log(percentComplete*100);
addProgress(percentComplete*100);
}
});
return xhr;
},
The entire codes:
JQuery;
PHP URL
The Error: When a upload a file and submit the form, the console.log(evt.total); and console.log(evt.loaded); print the same value, and them the progress bar is fully, but the Ajax continues requesting the PHP file and my table is empty yet.
So what I can do to my progress bar work with the response from PHP file?
I am not sure about the loading, Even I am in search of something that shows how much is complete. But I have a working code to upload CSV to Mysql.
<?php
if(!empty($_FILES["employee_file"]["name"]))
{
$connect = mysqli_connect("123.123.123.99","db_username","db_password","db_Name") or die('Unable To Connect');
$output = '';
$allowed_ext = array("csv");
$extension = end(explode(".", $_FILES["employee_file"]["name"]));
if(in_array($extension, $allowed_ext))
{
$file_data = fopen($_FILES["employee_file"]["tmp_name"], 'r');
fgetcsv($file_data);
while($row = fgetcsv($file_data))
{
$customerDetails = mysqli_real_escape_string($connect, $row[0]);
$cod = mysqli_real_escape_string($connect, $row[1]);
$trackingID = mysqli_real_escape_string($connect, $row[2]);
$shipmentType = mysqli_real_escape_string($connect, $row[3]);
$vendorName = 'eKart';
$query = "
INSERT INTO nss_delivery
(customerDetails, cod, trackingID, shipmentType, vendorName)
VALUES ('$customerDetails','$cod', '$trackingID', '$shipmentType', '$vendorName')
";
mysqli_query($connect, $query);
}
$select = "SELECT * FROM nss_delivery ORDER BY deliveryID DESC";
$result = mysqli_query($connect, $select);
$output .= '
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="25%">Customer Details</th>
<th width="35%">COD Amount</th>
<th width="10%">Tracking ID</th>
<th width="20%">ShipmentType</th>
<th width="5%">Vendor Name</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["deliveryID"].'</td>
<td>'.$row["customerDetails"].'</td>
<td>'.$row["cod"].'</td>
<td>'.$row["trackingID"].'</td>
<td>'.$row["shipmentType"].'</td>
<td>'.$row["vendorName"].'</td>
</tr>
';
}
$output .= '</table>';
echo $output;
}
else
{
echo 'Error1';
}
}
else
{
echo "Error2";
}
?>

Displaying MYSQL table data dynamically through JSON, Jquery and PHP

I am trying to display the contents of a "users" table in my MYSQL database using PHP,JQUERY and JSON.
Here is the PHP file:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "ITSM";
$tableName = "signup_and_login_table";
include 'database_connection.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName");
$array = mysql_fetch_row($result);
echo json_encode($array);
?>
On my HTML page i have a simple table im trying to target:
<table id="personDataTable">
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</table>
This is the jquery ajax, I want it to loop through all the users and other table entities to display all the contents of the Database table on the page, Im currently just getting "undefined".
$(function ()
{
$.ajax({
url: 'CMGetdata.php',
data: "",
dataType: 'json',
success: function(data, textStatus, jqXHR) {
drawTable(data);
}
});
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
console.log("test");
function drawRow(rowData) {
var row = $("<tr />")
$("#personDataTable").append(row);
row.append($("<td>" + rowData.id + "</td>"));
row.append($("<td>" + rowData.firstName + "</td>"));
row.append($("<td>" + rowData.lastName + "</td>"));
}
Any assistance to be pointed in the correct direction would be greatly appreciated thanks.
Try This-
$result =$con->query("SELECT * FROM tableName");
$array = $result ->fetch_all(MYSQLI_ASSOC);
foreach($array as $array)
{
$array['example'];
//another
}

how to search data from an output table using php ajax

I new to php, ajax and mysql. I am trying to build a web application where i get an output table from my database. My question is what code should i use if i want to search another table using the current output table for eg
name surname
john smith
is my out put table, if i click on smith it should search other table containing data about smith
My js code is
$(function myFunction() {
$("#lets_search").bind('submit',function() {
var value = $('#str').val();
var value1= $('#str1').val();
$.post('test_refresh.php',{value:value,value1:value1}, function(data){
$("#search_results").html(data);
});
return false;
});
});
My Php code is
<?php
$conn = mysql_connect("localhost", "root", "") or die(mysql_error());
$db = mysql_select_db("cancer database") or die(mysql_error());
echo"";
/*$query = mysql_query("SELECT * FROM tbl_cancer_database
WHERE gene_symbol LIKE '".$_POST['value']."'
OR gene_name LIKE '".$_POST['value']."'
OR gene_id LIKE '".$_POST['value']."'
OR gene_locus LIKE '".$_POST['value']."'
OR function LIKE '%".$_POST['value']."%'
OR alteration_in_cancer LIKE '".$_POST['value']."'
OR reference LIKE '".$_POST['value']."'
");*/
$query = mysql_query("SELECT * FROM tbl_cancer_database
WHERE gene_name LIKE '".$_POST['value']."'
and gene_id LIKE '".$_POST['value1']."'
");
echo '<br />';
echo "You have searched for ".$_POST['value']." and ".$_POST['value1']."";
echo '<br />';
echo '<br />';
echo '<table>';
echo "<tr>
<th bgcolor=silver>Sr. No.</th>
<th bgcolor=silver>Gene Symbol</th>
<th bgcolor=silver>Gene Name</th>
<th bgcolor=silver>Gene Id</th>
<th bgcolor=silver>Gene locus</th>
<th bgcolor=silver>Function</th>
<th bgcolor=silver>Alteration in cancer</th>
<th bgcolor=silver>Reference</th></tr>";
while ($data = mysql_fetch_array($query)) {
echo '<tr style="background-color:pink;">
<td>'.$data["id"].'</td>
<td>'.$data["gene_symbol"].'</td>
<td>'.$data["gene_name"].'</td>
<td>'.$data["gene_id"].'</td>
<td>'.$data["gene_locus"].'</td>
<td>'.$data["function"].'</td>
<td>'.$data["alteration_in_cancer"].'</td>
<td>'.$data["reference"].'</td>
</tr>';
}
echo '</table>';
?>
Any help would be greatly appreciated.
First of all add a class that uniquely identifies each of your table data.
So your table would look like this
<table>
<tr>
<td class="fistname">John</td>
<td class="lastname">Smith</td>
</tr>
</table>
Then your javascript would look like this
$(function myFunction() {
$("#lets_search").bind('submit',function() {
var value = $('#str').val();
var value1= $('#str1').val();
$.post('test_refresh.php',{value:value,value1:value1}, function(data){
$("#search_results").html(data);
initializeClick();
});
return false;
});
});
function initializeClick(){
$('.firstname').click(function(){
var sSearchValue = $(this).text();
$.post('PAGE TO SEARCH YOUR OTHER TABLE',{value:sSearchValue}, function(data){
//CAN DO WHAT EVER YOU WANT WITH THE RESULTS HERE
});
});
}
Also keep in mind to escape characters when they are output on the html

Display mysql database report in several pages

I have a mysql database with some data. Now i want to show you mysql data to all. with edit option.
<?php
$username = "VKSolutions";
$password = "VKSolutions#1";
$hostname = "VKSolutions.hostedresource.com";
$database = "VKSolutions";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($database,$dbhandle)
or die("Could not select $database");
$query= 'SELECT * FROM customer_details';
$result = mysql_query($query)
or die ('Error in query');
echo '<table width=80% border=1 align="center">';
echo '<tr><td><b>ID</b></td><td width="20px"><b>Name</b></td><td width="25px"> <b>Telephone</b></td><td width="30px"><b>E-mail</b></td><td width="20px"><b>Country Applying for</b></td><td width="20px"><b>Visa Categeory</b></td><td width="20px"><b>Other Categeory</b></td><td width="20px"><b>Passport No</b></td><td width="50px"> <b>Remarks</b></td></tr>';
while ($row=mysql_fetch_row($result))
{
echo '<tr>';
echo '<td>'.$row[0].'</td>';
echo '<td>'.$row[1].'</td>';
echo '<td>'.$row[2].'</td>';
echo '<td>'.$row[3].'</td>';
echo '<td>'.$row[4].'</td>';
echo '<td>'.$row[5].'</td>';
echo '<td>'.$row[6].'</td>';
echo '<td>'.$row[7].'</td>';
echo '<td>'.$row[8].'</td>';
echo '</tr>';
}
echo '</table>';
mysql_free_result($result);
mysql_close($dbhandle);
?>
I need some modifications in this code like
1) MySql data displays in a single page. but not i want. I need to display data with several pages like (page1,page2,page3,.....page54... etc)
2) and also give edit option when a user want to change.
Thanks.
You need to add LIMIT to your select statement.
If you read here:
http://dev.mysql.com/doc/refman/5.0/en/select.html
So you would change your statement to:
SELECT * FROM customer_details LIMIT 0,20
This would get the first 20 records, then to get the next lot of results:
SELECT * FROM customer_details LIMIT 20,20
The numbers after the limit are, the first one is where it still start and the second one is how many to return.
I hope this points you in the right direction.
hey if you want to show data with pages use pagination also if you want to edit the value than you have to show data in a text box like this and send via form
<?php
$username = "VKSolutions";
$password = "VKSolutions#1";
$hostname = "VKSolutions.hostedresource.com";
$database = "VKSolutions";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($database,$dbhandle)
or die("Could not select $database");
$query= 'SELECT * FROM customer_details';
$result = mysql_query($query)
or die ('Error in query');
?>
<table width=80% border=1 align="center" id=pag>
<tr><td><b>ID</b></td><td width="20px"><b>Name</b></td><td width="25px"><b>Telephone</b></td><td width="30px"> <b>E-mail</b></td><td width="20px"><b>Country Applying for</b></td><td width="20px"><b>Visa Categeory</b></td><td width="20px"><b>Other Categeory</b></td><td width="20px"><b>Passport No</b></td><td width="50px"><b>Remarks</b></td></tr>
<?php
while ($row=mysql_fetch_row($result))
{
?>
<tr>
<td><input type="text" name="newid" value="<?php echo $row[0];?>" /></td>
<td><input type="text" name="newname" value="<?php echo $row[1];?>" /></td>
<td><input type="text" name="aaaa" value="<?php echo $row[2];?>" /></td>
......
</tr>
<?php
}
?>
</table>
//pagination code
<div class="pagination" align="center" >
<div id="pageNavPosition"></div>
</div>
<script type="text/javascript"><!--
var pager = new Pager('pag',10); // pag is id of table and 10 is no of records you want to show in a page. you can change if you want
pager.init();
pager.showPageNav('pager', 'pageNavPosition');
pager.showPage(1);
//--></script>
</div>
<?php
mysql_free_result($result);
mysql_close($dbhandle);
?>
in the head section add this.
<script type="text/javascript" src="paging.js"></script> /* adding javascript pagination source page */
code for paging.js goes here. just copy and paste the code in a file name paging.js
function Pager(tableName, itemsPerPage) {
this.tableName = tableName;
this.itemsPerPage = itemsPerPage;
this.currentPage = 1;
this.pages = 0;
this.inited = false;
this.showRecords = function(from, to) {
var rows = document.getElementById(tableName).rows;
// i starts from 1 to skip table header row
for (var i = 1; i < rows.length; i++) {
if (i < from || i > to)
rows[i].style.display = 'none';
else
rows[i].style.display = '';
}
}
this.showPage = function(pageNumber) {
if (! this.inited) {
alert("not inited");
return;
}
var oldPageAnchor = document.getElementById('pg'+this.currentPage);
oldPageAnchor.className = 'pg-normal';
this.currentPage = pageNumber;
var newPageAnchor = document.getElementById('pg'+this.currentPage);
newPageAnchor.className = 'pg-selected';
var from = (pageNumber - 1) * itemsPerPage + 1;
var to = from + itemsPerPage - 1;
this.showRecords(from, to);
}
this.prev = function() {
if (this.currentPage > 1)
this.showPage(this.currentPage - 1);
}
this.next = function() {
if (this.currentPage < this.pages) {
this.showPage(this.currentPage + 1);
}
}
this.init = function() {
var rows = document.getElementById(tableName).rows;
var records = (rows.length - 1);
this.pages = Math.ceil(records / itemsPerPage);
this.inited = true;
}
this.showPageNav = function(pagerName, positionId) {
if (! this.inited) {
alert("not inited");
return;
}
var element = document.getElementById(positionId);
var pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-normal"> &#171 Prev </span> ';
for (var page = 1; page <= this.pages; page++)
pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> ';
pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-normal"> Next ยป</span>';
element.innerHTML = pagerHtml;
}
}

Categories