Sunday, October 6, 2019

[SOLVED] PHP, MySQL & React REST API Tutorial with Example Form

PHP is a very robust backend technology. Combined with MySQL it has withstood the test of time and are security wise good enough solutions. What makes these technologies even more popular is their ease of learning.

Recently it is a trend in the industry to have Web APIs serve website requests. On the front end use of Javascript frameworks like Angular JS and/or React JS or Vue.js makes the front end independent of the backend.
Why I say that is because for any data request that comes to the server, These front end client facing Apps can be changed without the back-end requiring any changes. Not only that, the back end can be upgraded to newer technologies without any changes to the front end app.
This decoupling is possible with the miracle technologies of Client Side Apps and Single Page Applications using frameworks such as AngularJS or ReactJS.

A React Application that I am going to focus on now will be responsible for the View or the rendering of data to the client. It does this task efficiently by the use of a concept called Virtual DOM. Updating the DOM is faster if we know which nodes in the DOM tree have changed. A Diffing algorithm used by React-JS does this efficiently.

Coming to the example part of my blog, I am going to improvise on an existing app that was written quite some time back and does not work well(Has errors while running). If you are interested in the non working application, that you could copy code from, then read this article in the site techiedairies.

PHP, MySQL & React REST API Tutorial with Example Form

Otherwise, you may continue to read on to know the differences that need to be made to make the program work.
Pre-Requisites:
1) PHP 2) MySQL 3) ReactJS 

If you have a set up with XAMPP/WAMP/LAMP that will have all these except ReactJS which you need to install and for that you need NodeJS.

Now,

WebAPIs that we write will serve rows of a table. All the rows are displayed in the react app and there is provision to add another row or post info to the PHP server.

First thing after having the prerequisites is you should expect to get errors in the browser. This is common for all website projects. Next is you should listen to those who have trodden this path. So the biggest errors you may get is in the PHP file and you may avoid some heartburn and save time by making following changes.

in contacts.php file there are some mistakes that need to be set right:

This is the correct code:
if ($method == 'GET') {
    echo '[';
    for ($i=0 ; $i<mysqli_num_rows($result) ; $i++) {
      echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
    }
    echo ']';
  } elseif ($method == 'POST') {
    echo json_encode($result);
  } else {
    echo mysqli_affected_rows($con);
  }

Where you don't set the array brackets based on existence of id field in the request.

Another thing is 
  componentDidMount() {
    const url = 'http://localhost/api/abc/contacts.php?id='
    axios.get(url).then(response => response.data)
    .then((data=> {
      this.setState({ contacts: data })
      console.log(this.state.contacts)
     })
  }

in your react app componentDidMount() function, the URL should be as shown above.
There should be an id field without any data which our php server checks. If no ID field is given the server sends an error header like this.


And that is because of the following thing:

So the extra error makes the contacts array not be parsed properly.

Now Another error you may encounter is the CORS issue. I solved this via a temporary solution of adding a CORS Access-Control-Allow-Origin extension in chrome.


If everything is fine, but only cors issue is blocking your access request, then you will get the following screen:

If you set the CORS button ON then you will get the following output:

Which is nothing but the output of the following MySQL database table:

mysql> select * from contacts;
+----+--------+------------------------+-----------+---------+---------+
| id | name   | email                  | city      | country | job     |
+----+--------+------------------------+-----------+---------+---------+
|  1 | mukesh | bmk@gmail.com          | bengaluru | India   | AC      |
|  2 | muk1   | bmkamath20000@gmail.co | bengal    | india   | driver  |
|  3 | kkjfev | suresh.kamath.104      | bng       | ind     | plumber |
+----+--------+------------------------+-----------+---------+---------+
3 rows in set (0.00 sec)

Another thing is in the contactsform.js component that you use to post data to the PHP server,

The axios function should get appropriate URL of your web service like this:

axios({
            method: 'post',
            url: 'http://localhost/api/abc/contacts.php',
            data: formData,
            config: { headers: {'Content-Type': 'multipart/form-data' }}
        })

Here my contacts.php file location is /api/abc within the server www folder.

I hope you have a smooth learning curve... Cheers!!!

No comments:

Post a Comment