HomePHP Page 2 - PHP and JavaScript Interaction: Storing Data in the Client, part 3
Records wanted! Fetching data from tables - PHP
In the final article in our series about using PHP and JavaScript to store data on the client side, we will be building on what we learned about server and client interaction to create a JavaScript-based paginating system.
Despite the fact that we've discussed in previous articles the significant limitations of storing database records directly in a client's machine (specifically in RAM), there are some situations where this approach might be pretty useful. In small intranet environments, where the volume of data is rather limited, with applications running with controlled software and hardware resources, this method may find its place. However, anything else falling outside this category certainly should be considered inefficient.
Having stated this disclaimer, it's time to look at the JavaScript functions needed to create the paging system. But, wait a minute! In order to paginate records we need to fetch them from a database first, right? So, our first task is to connect to the MySQL server, perform a SELECT query against a database, and populate a JavaScript array with the retrieved data. Let's do it in a procedural way:
$db=mysql_connect('dbhost','user','password') or die('Error connecting to the server'. mysql_error());
mysql_select_db('database') or die('Error selecting database');
$result=mysql_query('SELECT * FROM table') or die('Error performing query');
Now, if things work out just fine, we've hopefully obtained a result set. It's time to invoke our friendly "createJavaSCript()" function, for transferring the records to a JavaScript array, passing as parameters the result set and the name of the array to be generated. Just like this:
echo createJavaScript($result,'rows');
It's that simple. Our records happily reside on the "rows" array, waiting to be processed. Our fetched records are stored in the client, ready to be paginated. Let's define the JavaScript functions.