HomePHP Page 4 - PHP and JavaScript Interaction: Storing Data in the Client, part 1
Dealing with result sets - PHP
Modern websites demand heavy interaction between server-side and client-side programming. In the first part of this article series, we will implement a simple mechanism to make PHP and JavaScript interact, creating a function which can build an array structure and store information in it. It will allow for programmatic data manipulation without server interaction.
By now, we're halfway home. We've already seen how to build a JavaScript array from data files, right? Now, the function should be capable of working with database result sets, at least at a basic level. Fortunately, our function checks to see what type of data source has been provided. If the parameter $dataSource is a result set, then table records are extracted with a regular loop, and stored in the proper JavaScript array, following the same method aplicable in flat data files. The lines that extract table records and create the JavaScript array are listed below:
// check if we have a valid result set if(!$numRows=mysql_num_rows($dataSource)){ die('Invalid result set parameter'); } for($i=0;$i<$numRows;$i++){ // build JavaScript array from result set $javascript.=$arrayName.'['.$i.']="'; $tempOutput=''; foreach($row=mysql_fetch_array($dataSource,MYSQL_ASSOC) as $column){ tempOutput.=$column.' '; } $javascript.=trim($tempOutput).'";'; }
Luckily, we've stored database records in the dynamic array. Before we move on, a little explanation is in order here. Notice that inside the loop process we've retrieved each table field, separating them with a single blank space. Why did we do it that way? The reason is quite simple: by doing so, we can access each table field value later, by simply splitting the string of data returned by the function.
However, possible additions are probably valid too. We could have stored field values in a bi-dimensional JavaScript array, for further access. The flip side is that we'd be taking up even more client memory, making the overall storage a crash prone process. So, to keep things simple, we're using the first aproach.
Still following the function explanation? Good, because we're almost done.
Once the function has done its thing building the JavaScript array and populating it either with flat data files or database records, it must end up completing the code, adding a </script> closing tag, and returning the output, just like this:
As I told you before, we're almost done. Our function takes a file or database result set, generates an array structure with the values obtained, and finally returns the complete JavaScript code, ready to be included in any application for further processing.
Okay, it's time to test our function. Let's show a practical example to see how it can be used.