March 7

How to update a MySQL field in a table matrix

matrix table image

This is a tutorial on updating a unqiue mysql field in a matrix grid of elements by using PHP and jQuery.

In this tutorial, we are presuming you are familiar with PHP and MySQL.
This is the example we will use. The scenario is giving users access to special features on movies created by producers. This will be useful in the near future when producers have control of film distribution.

We start with the database design creating four tables.

  1. producers
  2. users
  3. Features
  4. feature_access

Step 1. Import schema

Copy paste the code or import the TEST.SQL file into phpMyAdmin (download file link at the bottom of tutorial).

The USERS and PRODUCERS tables are simplified to id and names. The FEATURES table has a foreign key to link the producer who made the feature. The FEATURE_ACCESS table contains 3 foreign keys, linking the 3 other tables. The additional field we are calling “access” is a BOOLEAN allowing NULL.
If you are wondering why were are allowing NULL values besides 0 and 1, it’s because we want the FEATURE_ACCESS records to exist regardless if they are active or not. More on this later.

Step 2. Create an empty file and name it features.php, this file will include HTML and PHP. Insert PHP code to connect to your database. I chose the method mysqli for simplicity of this tutorial.

js/ (for jQuery files or you can link directly to the CDN)

The HTML doctype is not important, but we will use HTML5. Make sure to include the jQuery framework and UI subset either locally or from the CDN. CSS is just to outline the table, which is the main element to display the features and yes, the table is used semantically in the form of a data matrix.

Step 3. In this step we are preparing two SELECT queries and arrays. The FEATURES will be for the column headers. The second query inner joins USERS as the row headers and FEATURE_ACCESS as the inner cells.

Let’s select the unique id and feature name where the PRODUCER_ID matches, because the table will represent features of one producer. For this example I will display the PRODUCER_ID in the cells for verification of data alignment in the table.

In the second query, we are selecting from two tables that’s why we are giving unique names followed by the “AS”. So the required filenames are:, -username from USERS

then, feature_access.producer_id, feature_access.feature_id,
feature_access.access from FEATURE_ACCESS

The join statement matches user_id from both tables but only from the one selected producer. The ORDER is very important because it will make the table useless if not correct. This allows the record order inserted into the database be irrelevant.

Next is to create two arrays to hold the data to be rendered in the table cells.
$feature_array = array(); $access_array = array();

Step 4. Now to execute the queries and push the results in to the arrays.

This first $result captures the $sql_features query by the method mysqli_query() taking in two variables, the database link $link and query statement. The die() method allows an error to display if the connection fails. We get the feature count to determine how many columns to display using the method mysqli_num_rows().

Using a while loop we push the associative arrays from the $result resource into the $features_array. Then we do the execute the same two steps for the other query $sql_featuers. If you want to see your progress using PHP’s print_r() or var_dump() methods, I’ve included echo output in <pre> tags because they so you can see the arrays better.</pre>
Now let’s create a new empty variable to hold the boolean for the access field and a IF statement for reading the $_POST. I add the functions is_numeric() and isset() in the if statement as they are the two essential variable to UPDATE the database record for feature_access.

$new_access = ”;
if ( $_POST && is_numeric($_POST[‘fid’]) && isset($_POST[‘access’]) ) {

matrix jquery post

Step 5. Process the POST data.

You should be on line 53 now so we can filter the POST data. Inside the IF {} we cast the feature_id as an integer and assign the $new_access variable from the user input. This is another IF ELSE statement which accepts a string of “true” provided from the HTML checkbox and sets the variable to a boolean of 0 or 1 because that’s how it’s recorded in the database.

The next line (62) we prepare a SELECT query to see if the exists. Execute the query and if the id exists, you get a valid resource to match in the next IF ELSE statement. But first we will add an ELSE statement if the ID does not exist, a simple string assignment goes to the variable $status = “Tour Access ID does not exist.”. Back inside the nested IF, we will process the record update.

Prepare the UPDATE query matching the and execute it. The following iF ELSE runs mysqli_query() method or dies. And that’s all there is for the database work.

6. In In this step we render the table with PHP inside the HTML.

Let’s skip to line 108, where it should be in inside the table row
tag. This will be the first cell so let’s place the producer_id in it using echo.

<tr class=”table_header”>
<th><? echo $producerid;?></th>

For the next line use a for loop to create the y-axis headers showing the features names. Count the loop iteration using the variable $feature_count we created earlier and echo table headers tags <th>, then the name echoing $feature_array using the counter variable $i for the multi-dimensional array. For the verification purposes, I am also echoing the feature_id. Now close the tag and i’ve added \n for reading the code easier in “source view”.

Close the for loop and create another one to show the user name with their unique feature access ids. Duplicate the loop, except use $access_count for number of iterations. The next line (121) which is an IF statement, is important because it determines when to create a new row. Within the next two lines you echo out table row <tr> and user names inside

tags. I’ve also included the user_id for visual verification.

This IF statement executes if the $feature_count divides the loop’s iteration into a zero. Line 125, we echo opening <td> tag followed by and <input> checkbox tag containing the value [fid] and if it is checked or not. Then we close the </input> tag and </td>.

This should out put your entire table followed by closing the final row and table tag.  You can confirm the data displayed by opening the feature.php file on your testing server.

Step 7.  For the final step to process the change we use jQuery to do an ajax call

Going to line 101, write the default jQuery document function to execute when page is loaded.  Then write a custom function binding a “change” event to all input tags with the class “.flipswitch”.

Inside this function we set a javascript variable to hold the parent tag <td> which will use for visual confirmation as a highlight.   You can uncomment the alert() line to confirm everything is working prior to the ajax all.  So the ajax method sends the “id” and “true” if checked strings to the same PHP page and hits the IF $_POST clause.

It the ajax call is a success, it will highlight the table cell for you by a fading out the color red.

After your first checkbox click, refresh the page to see if the change remain so you know the UPDATE occurred in the database.


Have any questions or comments to improve this tutorial?  Comment below!

Tags: , , , ,

Posted March 7, 2013 by Tom in category "Code

Leave a Reply