-0.8 C
New York
Sunday, September 19, 2021
HomeFirebaseCRUD operation with PHP and Firebase

CRUD operation with PHP and Firebase

CRUD operation is basic of any language. At first you have to go here and create a project.

Add a Firebase project.

Enter a project name.

crud operation
Enter your project name.

You can enable Google Analytics or not.

You can enable Google Analytics if you want.

Select Google Analytics account.

Select Google Analytics Default Account for Firebase or from your before account.

Now click on the “Continue” and you will land on the console page. Now click on the ‘Authentication’ tab, then ‘Get Started’.

Click on the Authentication tab,

Scroll below and add a domain without http or www.

Add your project domain without http or www.

After doing that click on the gear icon → Project Settings.

Click on the gear and go to Project Settings.

Go to “Service Account” tab and wait for sometimes. Then click on the “Generate new private key”, then ‘Generate key’. A json file will download.

Click on the Generate new private key

Now click on the “Realtime Database” → “Create Database”. A popup will open and select “United States (us-central1)” → Next.

Select “Test Mode” and then “Enable”.

A database will create and click on the database URL to copy.

Click to copy the database URL.

Now your Firebase console is ready to use. Then we’ve to ready our PHP code. At first, create a folder and install firebase/php through composer. You can find here the Firebase PHP doc.

composer require kreait/firebase-php

Create a ‘db.php’ file and paste the code.

<?php
// Include libraries
require_once 'vendor/autoload.php';

use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;

$factory = (new Factory)
    ->withServiceAccount(__DIR__ . '/your_downloaed_json_file.json')
    ->withDatabaseUri('your_database_url');
$database = $factory->createDatabase();

Data insert form ‘index.php’ file.

<h3>Data INSERT using Firebase and PHP</h3>
<form action="firbasecodeprocess.php" method="post">
    <div class="form-group mb-2">
        <input type="text" name="username" class="form-control" placeholder="Enter username">
    </div>
    <div class="form-group mb-2">
        <input type="text" name="email" class="form-control" placeholder="Enter email">
    </div>
    <div class="form-group mb-2">
        <input type="number" name="phoneno" class="form-control" placeholder="Enter phone number">
    </div>
    <div class="form-group">
        <button type="submit" name="save_push_data" class="btn btn-primary">Save Data</button>
    </div>
</form>

Above form action I have used ‘firbasecodeprocess.php’ file. Create a file with that name and it’s the insert code.

<?php
session_start();
require_once "firebasedb.php";

// Insert data
if (isset($_POST['save_push_data'])) {
    $username = $_POST['username'];
    $email = $_POST['email'];
    $phoneno = $_POST['phoneno'];

    $data = [
        'username'  => $username,
        'email'     => $email,
        'phoneno'   => $phoneno
    ];

    $ref = "contact/"; // I can use any table (contact/) name here. This name will automatically generate in Firebase and data will be stored under this table. That means I no need to create this table from Firebase console/dashboard area.

    $postData = $database->getReference($ref)->push($data);

    if ($postData) {
        $_SESSION['status'] = "Data inserted";
        header('location: index.php');
    } else {
        $_SESSION['status'] = "Data NOT inserted";
        header('location: index.php');
    }    
}

When I will click on the HTML “Save Data” button, table will be created automatically in Firebase and save data. To see it go to “Realtime Database” and you will the data.

With Firebase you no need to create database table fields like as MySQL.

Update code is almost same like the insert code. Just use ‘update()’ instead of ‘push()’.

$postData = $database->getReference($ref)->update($data);

Display all data from database.

<?php
$ref = "contact/";
$fetchData = $database->getReference($ref)->getValue();
foreach ($fetchData as $key => $row) {}

Now display data like:

<?= $row['username']; ?>
<?= $row['email']; ?>
<?= $row['phoneno']; ?>

The single data id belongs to “$key” variable. You can update or delete by using the data token ($key).

<a href="index.php?token=<?= $key; ?>" class="btn btn-primary btn-sm">Edit</a>

If you want to delete a data, you need to make a form like.

<form action="firbasecodeprocess.php" method="post">
    <input type="hidden" name="ref_token_delete" value="<?= $key; ?>">
    <button type="submit" class="btn btn-danger btn-sm" name="delete_data" onclick="return confirm('Are you sure to delete?')">Delete</button>
</form>

Process the form request.

if (isset($_POST['delete_data'])) {
    $token = $_POST['ref_token_delete'];
    $ref = "contact/" . $token;
    $deleteData = $database->getReference($ref)->remove();
    if ($deleteData) {
        $_SESSION['status'] = "Data deleted";
        header('location: index.php');
    } else {
        $_SESSION['status'] = "Data NOT deleted";
        header('location: index.php');
    }
}

Overall it was the create-read-update-delete (CRUD) operation with PHP and Firebase. If you have any question, feel free to ask me or post your comment below the post.

Leave a Reply

Most Popular

Recent Comments

%d bloggers like this: