How to make HTML template dynamic using Reactjs, PHP and MySQL


Before starting this tutorial, you have to complete the previous tutorial that converts any HTML template into reactJS project. How you can make a particular portion of the reactJS project dynamic using reactJS, PHP and MySQL is shown in this tutorial. You have to install xampp server for starting the steps of this tutorial.


1. Create a database named landscrapers and download the following SQL file to import the necessary table to complete this tutorial.


2. Create services folder under src folder. Add PostData.js under services folder.

export function PostData(type) {
if (type=="services") {
var BaseURL = 'http://localhost/reactproject/api/services.php';
} return new Promise((resolve, reject) =>{ fetch(BaseURL, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, }) .then((response) => response.json() .then((res) => { resolve(res); })) .catch((error) => { reject(error); }); }); }

3. Create another folder api under reactapp.

4. Go to api folder and create .htaccess file with the following code

RewriteEngine On
#RewriteBase /api/
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]

5. Create a php file named config.php under api folder for database connection and add the following code.

$db = new mysqli("localhost","root","","landscraper");
if(!$db) die("database connection error");

6. Create services.php under api folder and add the following code

require 'config.php'; 
$json = json_decode(file_get_contents('php://input'), true);
$query = "SELECT * FROM services";
$result = $db->query($query); 
$serviceData = mysqli_fetch_all($result,MYSQLI_ASSOC);
echo '{"serviceData":'.$services.'}';

7. Add the following code at the top of the Home class inside Home.js file to fetch data from MySQL using PHP.

constructor(props) {
  this.state = {
componentWillMount() {
getservices() {
  PostData('services').then((result) => {
  let responseJson = result;
    this.setState({services: responseJson.serviceData});

8. Remove the static portion of services from Home.js and add the following code in the services portion of the Home.js file to display the data from the services table of MySQL.

{, index) => {
var svgimg = `img/services/service-${item.serv_id}.jpg`;
return <li>
<div class="col-md-3 text-center">
<div class="service-media"> <img src={svgimg} alt=" " /> </div>
<div class="service-desc">
</div> </li>

8. Run the app from the browser.