php help

Frozodo

Fledgling Freddie
Joined
Sep 27, 2004
Messages
1,401
okay so i got this webpage im trying to delevop, however i runned into a brick wall. Im trying to get it to swap inbetween 10000 of records without changing the page does anyone know if this is possible if yes could you kindly post an i.e. as this is bugging the bib out of me right now...
thanks alot
 

Gahn

Resident Freddy
Joined
Jan 16, 2004
Messages
5,056
In .NET u would use a Gridview, no idea on php but am pretty sure there's something like that also.
Edit: may want to give a look here
 

SheepCow

Bringer of Code
Joined
Dec 22, 2003
Messages
1,365
As Jonty said, a nice bit of AJAX would be needed to do that. ASP.NET's GridView using AJAX (you just don't have to program it yourself).
 

TdC

Trem's hunky sex love muffin
Joined
Dec 20, 2003
Messages
30,801
smashing idea for a CAPTCHA replacement with a whiff of AJAX tbh :)
 

Frozodo

Fledgling Freddie
Joined
Sep 27, 2004
Messages
1,401
cheers guys time to read ^^ and learn! <3
 

Jonty

Fledgling Freddie
Joined
Dec 22, 2003
Messages
1,411
Hi guys

I'm quite reluctant to post this, since the code is sooo far from being a good example, but nevertheless someone requested a proof of concept and I had some free time at lunch.

Disclaimers

This code is really rough and ready. It has no error-checking, no redundancy, no regard for efficiency or elegant markup etc. Seriously, it's pretty much the bare minimum it takes to 'just work' and nothing else. Also, this is the first time I've ever used AJAX, so I just borrowed the code from the aforementioned W3Schools PHP and AJAX tutorial.

Process

Okay, there are four things we need:

  • Some SQL code for our database (no need if it already exists)
  • Some HTML for our webpage (to display the information)
  • Some AJAX functions (to handle the data requests)
  • Some PHP (to connect to the database and output the HTML)
SQL

The following SQL just creates a very simple table and inserts some examples.

Code:
-- Create a simple exampe table called 'sample'
CREATE TABLE `sample` (
`id` SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` TINYTEXT NOT NULL,
`age` SMALLINT NOT NULL,
`colour` TINYTEXT NOT NULL 
);

-- Insert some sample information
INSERT INTO `sample` (`id`, `name`, `age`, `colour`) VALUES
(NULL, 'Amy', '18', 'Red'),
(NULL , 'Bernice', '19', 'Blue'),
(NULL, 'Claire', '20', 'Green'),
(NULL , 'Dora', '21', 'Yellow'),
(NULL, 'Elly', '22', 'Pink'),
(NULL , 'Fran', '23', 'Orange');
HTML

The two most important elements here are the <script> tag (which includes the AJAX functions) and the <div> tag (which will contain our tabulated information).

Code:
<html>
<head>
	<!-- Include the AJAX scripts -->
	<script src="table.js" type="text/javascript"></script>
</head>

<body>

<div id="information"></div>

</body>
</html>
Javascript

The AJAX code just sends and receives requests to our PHP script for database information.

The only information we need to send is the range of rows we want (this is the 'LIMIT' attribute in MySQL's 'SELECT' function). For example, '0,2' means start at row 0 (this is the offset, it's not actually returned as part of the information) and return the next 2 rows (i.e. 1 and 2). Another example, '5,3', would mean start at row 5 (the offset) and return the next 3 rows (i.e. 6,7,8).

The information we receive is the HTML table and page links. Our PHP code generates all this, so the only thing our AJAX code needs to do is update our webpage.

Note that we call our AJAX function when the page first loads, and then whenever the user clicks one of our page links (as detailed below).

Code:
var xmlHttp

// Sends the request for information
function ajax_table (range)
{
	xmlHttp = GetXmlHttpObject();

	// Output a message if the browser doesn't support AJAX
	if (xmlHttp == null)
	{
		alert ("Sorry!");
		return;
	}

	// Contstruct the HTTP address (PHP file name + 'q' variable containing the range + 'sid' random session number
	var address = "table.php?q=" + range + "&sid=" + Math.random();

	// Send the request for information
	xmlHttp.onreadystatechange = stateChanged;
	xmlHttp.open("GET", address, true);
	xmlHttp.send(null);
}

// Output the PHP-generate HTML inside the 'information' <div> container
function stateChanged ()
{
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete")
	{
		document.getElementById("information").innerHTML = xmlHttp.responseText;
	}
}

// Necessary for AJAX cross-browser compatibility
function GetXmlHttpObject()
{
	var xmlHttp = null;

	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	}
	catch (e)
	{
		//Internet Explorer
		try
		{
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}

	return xmlHttp;
}

// Call the function when the page first loads (the request is for the first page)
window.onload = ajax_table('0,2');
PHP

Our PHP code operates just like normal, there's nothing special because it's AJAX. It connects to our database, retrieves the information we want, generates a HTML table to show the information, and generates some HTML page links.

Obviously the database login details need to be changed to whatever you're using. Also, there is a variable '$rows_per_page' which determines - you guessed it - how many rows of information you want to display per page.

The present page links solution isn't viable for massive amounts of information, but you can see the vital thing is the 'onclick' attribute which calls our AJAX function.

Code:
<?php
// Connect to the database
$database = mysql_connect("localhost", "username", "password");
mysql_select_db("database", $database);

// Retrieve the desired range of rows from the query string
$range = $_GET["q"];
// Set how many rows you want displayed per page
$rows_per_page = 2;

// Count the total number of rows (used for calculating the page numbers)
$count = mysql_query("SELECT COUNT(`id`) FROM `sample`");
// Retrieve the desired information
$data = mysql_query("SELECT * FROM `sample` LIMIT $range");

// Print the table header HTML ('\n' is a type of line-break character, so the source code is easier to read)
echo "<table>\n";
echo "	<tr>\n";
echo "		<th>First Name</th>\n";
echo "		<th>Age in Years</th>\n";
echo "		<th>Favourite Colour</th>\n";
echo "	</tr>\n";

// Print each desired row in HTML
while ($row = mysql_fetch_array($data))
{
	echo "	<tr>\n";
	printf("		<td>%s</td>\n", $row['name']);
	printf("		<td>%s</td>\n", $row['age']);
	printf("		<td>%s</td>\n", $row['colour']);
	echo "	</tr>\n";
}

// Print the table footer HTML
echo "</table>\n";

// Calculate the total number of rows
$total_rows = mysql_result($count, 0);
// Calculate the total number of pages needed ('ceil' rounds the figure up)
$total_pages = ceil($total_rows / $rows_per_page);

// Print the necessary links for each page
for ($i=0; $i<$total_pages; $i++)
{
	printf('<a href="#" onclick="ajax_table(\'%s,%s\')">Page %s</a> ', $i*$rows_per_page, $rows_per_page, $i+1);
}

// Close the database connection
mysql_close($database);
?>
Anyway, there you go, I told you it was rough and ready! You can view a working example to see how it functions.

Please note this code is provided as-is. Lunchtimes aside, I'm sadly too busy to provide anykind of proper support. Anyway, at least you can get some ideas, although the code needs sooo much refining, so please don't think this is 'how it should be done'. I'd personally check out W3Schools website for lots of useful information, tutorials, and examples (and 'no', I'm not affilliated with them, it just happens to be a handy website).

Good luck!

Kind regards
 

Chilly

Balls of steel
Joined
Dec 22, 2003
Messages
9,046
bloody ell Jonty :p

What I would say is that if you were going to use jonty's code as a basis for your own, make sure you sprinkle a lot of mysql_real_escape_string()'s around.

Also, I've just finished writing my very own little AJAX "framework" for use in a couple of my sites. Its nice that yahoo and google et al release their toolkits but 99/100 times they are too complex for what you actually need - which in my case is a simple server/client model with solid authentication and completely flexible usage (nearly).
 

Chilly

Balls of steel
Joined
Dec 22, 2003
Messages
9,046
Having just looked at that gridview and the corresponding demo, its looks nice but under the hood its a bit grubby. The page source is HUGE for what it is due to style information embedded in table element. This could be fixed by putting a class name instead of a style string and then taking the style information to the CSS page where it belongs.
 

Jonty

Fledgling Freddie
Joined
Dec 22, 2003
Messages
1,411
Hi guys

Good tips, Chilly :)

With regards writing your own code and/or framework, I think it's a great way to learn. Yes, it takes time, but writing things yourself really does make learning and remembering easier (self-discovery is a powerful thing). And as Chilly rightly says, general frameworks may be handy at times, but they try to cater for a wide variety of scenarios which in turn means they can be excessive for simple tasks.

Kind regards
 

Users who are viewing this thread

Top Bottom