Connect your WordPress application to a Firebase database

Blog

Firebase is a real-time non-reiational database provided by google. You can create this database under your google account. You can access the db directly through javascript and other technologies. You do not need to create the structure/schema of the database as you normally have to do in case of relational databases. You can save the data along with its schema directly through the script, as going to be demonstrated in the following example.

Visit https://console.firebase.google.com, create your Firebase database project. Get the required configuration code for your platform (iOS, Android or plain HTML/Javascript)

For details and documentations on Firebase visit:
https://firebase.google.com/
https://firebase.google.com/docs/

Write data to the database

Copy the code snippet from your Firebase project and paste in your javascript script, dbaccess.js.

dbaccess.js:

/* Initialize Firebase *

var config = {
    apiKey: "<Your API Key>",
    authDomain: "<YourAuthDomain>.firebaseapp.com",
    databaseURL: "<YourFirebaseDatabaseUrl>",
    projectId: "<YourProjectId>",
    storageBucket: "<StorageBucket>",
    messagingSenderId: "<YourMessageSenderId>"
};
firebase.initializeApp(config);

To write records in the database, assuming you want to have name, rank and score fields/nodes under the main node Players in your database.

writeNewRec(“John Smith”, “1”, “1010”);
writeNewRec(“Allan Donald”, “4”, “1090”)

function writeNewRec(name1, rank, score) {
var postData = {
Name: name1,
Rank: rank,
Score: score
};

// Get a key for the new Post.
var newPostKey = firebase.database().ref().child(‘Players’).push().key;
var updates = {};
updates[‘/Players/’ + newPostKey] = postData;
firebase.database().ref().update(updates);
}

Get the list of child nodes/records of the parent node

Also paste the following code at some appropriate place in the above js file. This codesnippet fetches all nodes/records under Players node. The returned list (data) is iterated with forEach structure so that each row/record is captured from it. An html table is then built with the help of the grabbed data.

var tblrow = '';
var PlayersRef = firebase.database().ref('Players/');
PlayersRef.once('value', function(data)
{ 
    data.forEach(function(childData) {
        tblrow = '<tr>';
        tblrow += '<th scope="row">' +childData.val().Rank+ '</th>';
        tblrow += '<td>' +childData.val().Name+ '</td>';
        tblrow += '<td>' +childData.val().Score+ '</td>';
        tblrow += '</tr>';

        $('.table-responsive').eq(0).find('tbody').append(tblrow);
    });
});

In the functions.php write these lines. They will enqueue the required firebase.js and our own javascript file dbaccess.js to get included in our WordPress infrastructure. These js files are included only for the “score-board” page or template (e.g, http://mywpsite.com/score-board) so that whenever the page gets called it connects to firebase db and update it with the fresh Players’ score

if ( strpos($_SERVER['REQUEST_URI'], 'score-board') ){
    wp_enqueue_script( 'firebase', 'https://www.gstatic.com/firebasejs/5.8.2 /firebase.js', array ( 'jquery' ), 1.1, true);


    /* Load database access script (above code). */
    wp_enqueue_script( 'dbaccess', get_template_directory_uri() . '/js/dbaccess.js', array ( 'jquery' ), 1.1, true);
}


2 thoughts on “Connect your WordPress application to a Firebase database

  1. Hi there,

    Our cheap online marketplace for freelancers offers a unique opportunity for businesses to access top talent at very affordable rates. Our platform makes it easy to find, hire, and manage freelancers, so you can focus on growing your business. Plus, with our low rates, you’ll save money compared to traditional staffing solutions.

    Check out our top freelancers: https://bit.ly/FreelancerMarket

    Best regards,
    Joanna Ratcliffe Marketing Manager @Freelancer Marketplace

  2. You must participate in a contest for among the finest blogs on the web. I’ll recommend this website!

Leave a Reply

Your email address will not be published. Required fields are marked *