Cara menggunakan connect php to firebase

Connect Mysql Php To Firebase Hosting 2022. First, go to the cpanel home and choose option files >> file manager. Exporting your firebase data into a json file.

Cara menggunakan connect php to firebase
Localhost Phpmyadmin Database Connection from b919rickboone.blogspot.com

Pdo will work on 12 different database systems, whereas mysqli will only work with mysql databases. The firebase cli makes it easy to set up a new hosting project, run a local development server, and deploy content.: Add your static assets to a local project directory, then run firebase init to connect the directory to a firebase project.

  • First, Keep In Mind That Firebase Uses Nosql Database Technology.
  • First, Go To The Cpanel Home And Choose Option Files >> File Manager.
  • Edited May 30 At 21:49.
  • The Firebase Cli Makes It Easy To Set Up A New Hosting Project, Run A Local Development Server, And Deploy Content.:
  • Pick One Of The Apps As A Trigger, Which Will Kick Off Your Automation.

First, Keep In Mind That Firebase Uses Nosql Database Technology.

What can you do instead, is to check your mysql database for new rows, and every time a new row is inserted, add that data to firebase. Exporting your firebase data into a json file. Firebase only supports hosting for static websites.

First, Go To The Cpanel Home And Choose Option Files >> File Manager.

If all your clients are then subscribing/watching the changes to your firebase. In the next window go to the public_html directory and upload the local file by clicking the upload icon from the upper menu. Pdo will work on 12 different database systems, whereas mysqli will only work with mysql databases.

Edited May 30 At 21:49.

We can replace the name with whatever we want. What we look for in the best web hosting for php mysql 1. Once you have done this, follow the steps given below:

The Firebase Cli Makes It Easy To Set Up A New Hosting Project, Run A Local Development Server, And Deploy Content.:

So, if you have to switch your project to use another database, pdo makes the process easy. The technical part can be the language of your choice. But, just make sure the page has a.php extension.

Pick One Of The Apps As A Trigger, Which Will Kick Off Your Automation.

You can instead host on their google cloud platform, unless you. Converting the json file into a csv file. Connect mysql database with php script in cpanel.

In this project you’ll build an ESP32 or ESP8266 client that makes an HTTP POST request to a PHP script to insert data (sensor readings) into a MySQL database.

Cara menggunakan connect php to firebase

You’ll also have a web page that displays the sensor readings, timestamp and other information from the database. You can visualize your data from anywhere in the world by accessing your own server.

As an example, we’ll be using a BME280 sensor connected to an ESP board. You can modify the code provided to send readings from a different sensor or use multiple boards.

In order to create build this project, you’ll use these technologies:

  • ESP32 or ESP8266 programmed with Arduino IDE
  • Hosting server and domain name
  • PHP script to insert data into MySQL and display it on a web page
  • MySQL database to store readings

1. Hosting Your PHP Application and MySQL Database

The goal of this project is to have your own domain name and hosting account that allows you to store sensor readings from the ESP32 or ESP8266. You can visualize the readings from anywhere in the world by accessing your own server domain. Here’s a high level overview:

Cara menggunakan connect php to firebase

I recommend using one of the following hosting services that can handle all the project requirements:

  • Bluehost (user-friendly with cPanel): free domain name when you sign up for the 3-year plan. I recommend choosing the unlimited websites option;
  • Digital Ocean: Linux server that you manage through a command line. I only recommended this option for advanced users.

Those two services are the ones that I use and personally recommend, but you can use any other hosting service. Any hosting service that offers PHP and MySQL will work with this tutorial. If you don’t have a hosting account, I recommend signing up for Bluehost.

Get Hosting and Domain Name with Bluehost »

When buying a hosting account, you’ll also have to purchase a domain name. This is what makes this project interesting: you’ll be able to go your domain name (http://example-domain.com) and see your ESP readings.

If you like our projects, you might consider signing up to one of the recommended hosting services, because you’ll be supporting our work.

Note: you can also run a LAMP (Linux, Apache, MySQL, PHP) server on a Raspberry Pi to access data in your local network. However, the purpose of this tutorial is to publish readings in your own domain name that you can access from anywhere in the world. This allows you to easily access your ESP readings without relying on a third-party IoT platform.

2. Preparing Your MySQL Database

After signing up for a hosting account and setting up a domain name, you can login to your cPanel or similar dashboard. After that, follow the next steps to create your database, username, password and SQL table.

Creating a database and user

1. Type “database” in the search bar and select “MySQL Database Wizard”.

Cara menggunakan connect php to firebase

2. Enter your desired Database name. In my case, the database name is esp_data. Then, press the “Next Step” button:

Cara menggunakan connect php to firebase

Note: later you’ll have to use the database name with the prefix that your host gives you (my database prefix in the screenshot above is blurred). I’ll refer to it as example_esp_data from now on.

3. Type your Database username and set a password. You must save all those details, because you’ll need them later to establish a database connection with your PHP code.

Cara menggunakan connect php to firebase

That’s it! Your new database and user were created successfully. Now, save all your details because you’ll need them later:

  • Database name: example_esp_data
  • Username: example_esp_board
  • Password: your password

Creating a SQL table

After creating your database and user, go back to cPanel dashboard and search for “phpMyAdmin”.

Cara menggunakan connect php to firebase

In the left sidebar, select your database name example_esp_data and open the “SQL” tab.

Cara menggunakan connect php to firebase

Important: make sure you’ve opened the example_esp_data database. Then, click the SQL tab. If you don’t follow these exact steps and run the SQL query, you might create a table in the wrong database.

Copy the SQL query in the following snippet:

CREATE TABLE SensorData (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    sensor VARCHAR(30) NOT NULL,
    location VARCHAR(30) NOT NULL,
    value1 VARCHAR(10),
    value2 VARCHAR(10),
    value3 VARCHAR(10),
    reading_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

View raw code

Paste it in the SQL query field (highlighted with a red rectangle) and press the “Go” button to create your table:

Cara menggunakan connect php to firebase

After that, you should see your newly created table called SensorData in the example_esp_data database as shown in the figure below:

Cara menggunakan connect php to firebase

3. PHP Script HTTP POST – Insert Data in MySQL Database

In this section, we’re going to create a PHP script that is responsible for receiving incoming requests from the ESP32 or ESP8266 and inserting the data into a MySQL database.

If you’re using a hosting provider with cPanel, you can search for “File Manager”:

Cara menggunakan connect php to firebase

Then, select the public_html option and press the “+ File” button to create a new .php file.

Cara menggunakan connect php to firebase

Note: if you’re following this tutorial and you’re not familiar with PHP or MySQL, I recommend creating these exact files. Otherwise, you’ll need to modify the ESP sketch provided with different URL paths.

Create a new file in /public_html with this exact name and extension: post-esp-data.php

Cara menggunakan connect php to firebase

Edit the newly created file (post-esp-data.php) and copy the following snippet:

connect_error) {
            die("Connection failed: " . $conn->connect_error);
        } 
        
        $sql = "INSERT INTO SensorData (sensor, location, value1, value2, value3)
        VALUES ('" . $sensor . "', '" . $location . "', '" . $value1 . "', '" . $value2 . "', '" . $value3 . "')";
        
        if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
        } 
        else {
            echo "Error: " . $sql . "
" . $conn->error; } $conn->close(); } else { echo "Wrong API Key provided."; } } else { echo "No data posted with HTTP POST."; } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; }

View raw code

Before saving the file, you need to modify the $dbname, $username and $password variables with your unique details:

// Your Database name
$dbname = "example_esp_data";
// Your Database user
$username = "example_esp_board";
// Your Database user password
$password = "YOUR_USER_PASSWORD";

After adding the database name, username and password, save the file and continue with this tutorial. If you try to access your domain name in the next URL path, you’ll see the following:

http://example-domain.com/post-esp-data.php

Cara menggunakan connect php to firebase

4. PHP Script – Display Database Content

Create another PHP file in the /public_html directory that will display all the database content in a web page. Name your new file: esp-data.php

Cara menggunakan connect php to firebase

Edit the newly created file (esp-data.php) and copy the following code:



connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id, sensor, location, value1, value2, value3, reading_time FROM SensorData ORDER BY id DESC";

echo '';
 
if ($result = $conn->query($sql)) {
    while ($row = $result->fetch_assoc()) {
        $row_id = $row["id"];
        $row_sensor = $row["sensor"];
        $row_location = $row["location"];
        $row_value1 = $row["value1"];
        $row_value2 = $row["value2"]; 
        $row_value3 = $row["value3"]; 
        $row_reading_time = $row["reading_time"];
        // Uncomment to set timezone to - 1 hour (you can change 1 to any number)
        //$row_reading_time = date("Y-m-d H:i:s", strtotime("$row_reading_time - 1 hours"));
      
        // Uncomment to set timezone to + 4 hours (you can change 4 to any number)
        //$row_reading_time = date("Y-m-d H:i:s", strtotime("$row_reading_time + 4 hours"));
      
        echo '';
    }
    $result->free();
}

$conn->close();
?> 
ID Sensor Location Value 1 Value 2 Value 3 Timestamp
' . $row_id . ' ' . $row_sensor . ' ' . $row_location . ' ' . $row_value1 . ' ' . $row_value2 . ' ' . $row_value3 . ' ' . $row_reading_time . '

View raw code

After adding the $dbname, $username and $password save the file and continue with this project.

// Your Database name
$dbname = "example_esp_data";
// Your Database user
$username = "example_esp_board";
// Your Database user password
$password = "YOUR_USER_PASSWORD";

If you try to access your domain name in the following URL path, you’ll see the following:

http://example-domain.com/esp-data.php

Cara menggunakan connect php to firebase

That’s it! If you see that empty table printed in your browser, it means that everything is ready. In the next section, you’ll learn how to insert data from your ESP32 or ESP8266 into the database.

5. Preparing Your ESP32 or ESP8266

This project is compatible with both the ESP32 and ESP8266 boards. You just need to assemble a simple circuit and upload the sketch provided to insert temperature, humidity, pressure and more into your database every 30 seconds.

Parts Required

For this example we’ll get sensor readings from the BME280 sensor. Here’s a list of parts you need to build the circuit for this project:

  • ESP32 board (read Best ESP32 dev boards)
  • Alternative – ESP8266 board (read Best ESP8266 dev boards)
  • BME280 sensor
  • Jumper wires
  • Breadboard

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Cara menggunakan connect php to firebase

Schematics

The BME280 sensor module we’re using communicates via I2C communication protocol, so you need to connect it to the ESP32 or ESP8266 I2C pins.

BME280 wiring to ESP32

The ESP32 I2C pins are:

  • GPIO 22: SCL (SCK)
  • GPIO 21: SDA (SDI)

So, assemble your circuit as shown in the next schematic diagram (read complete Guide for ESP32 with BME280).

Cara menggunakan connect php to firebase

Recommended reading: ESP32 Pinout Reference Guide

BME280 wiring to ESP8266

The ESP8266 I2C pins are:

  • GPIO 5 (D1): SCL (SCK)
  • GPIO 4 (D2): SDA (SDI)

Assemble your circuit as in the next schematic diagram if you’re using an ESP8266 board (read complete Guide for ESP8266 with BME280).

Cara menggunakan connect php to firebase

Recommended reading: ESP8266 Pinout Reference Guide

ESP32/ESP8266 Code

We’ll program the ESP32/ESP8266 using Arduino IDE, so you must have the ESP32/ESP8266 add-on installed in your Arduino IDE. Follow one of the next tutorials depending on the board you’re using:

  • Install the ESP32 Board in Arduino IDE – you also need to install the BME280 Library and Adafruit_Sensor library
  • Install the ESP8266 Board in Arduino IDE – you also need to install the BME280 Library and Adafruit_Sensor library

After installing the necessary board add-ons, copy the following code to your Arduino IDE, but don’t upload it yet. You need to make some changes to make it work for you.

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

*/

#ifdef ESP32
  #include 
  #include 
#else
  #include 
  #include 
  #include 
#endif

#include 
#include 
#include 

// Replace with your network credentials
const char* ssid     = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// REPLACE with your Domain name and URL path or IP address with path
const char* serverName = "http://example.com/post-esp-data.php";

// Keep this API Key value to be compatible with the PHP code provided in the project page. 
// If you change the apiKeyValue value, the PHP file /post-esp-data.php also needs to have the same key 
String apiKeyValue = "tPmAT5Ab3j7F9";

String sensorName = "BME280";
String sensorLocation = "Office";

/*#include 
#define BME_SCK 18
#define BME_MISO 19
#define BME_MOSI 23
#define BME_CS 5*/

#define SEALEVELPRESSURE_HPA (1013.25)

Adafruit_BME280 bme;  // I2C
//Adafruit_BME280 bme(BME_CS);  // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK);  // software SPI

void setup() {
  Serial.begin(115200);
  
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) { 
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());

  // (you can also pass in a Wire library object like &Wire2)
  bool status = bme.begin(0x76);
  if (!status) {
    Serial.println("Could not find a valid BME280 sensor, check wiring or change I2C address!");
    while (1);
  }
}

void loop() {
  //Check WiFi connection status
  if(WiFi.status()== WL_CONNECTED){
    WiFiClient client;
    HTTPClient http;
    
    // Your Domain name with URL path or IP address with path
    http.begin(client, serverName);
    
    // Specify content-type header
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    
    // Prepare your HTTP POST request data
    String httpRequestData = "api_key=" + apiKeyValue + "&sensor=" + sensorName
                          + "&location=" + sensorLocation + "&value1=" + String(bme.readTemperature())
                          + "&value2=" + String(bme.readHumidity()) + "&value3=" + String(bme.readPressure()/100.0F) + "";
    Serial.print("httpRequestData: ");
    Serial.println(httpRequestData);
    
    // You can comment the httpRequestData variable above
    // then, use the httpRequestData variable below (for testing purposes without the BME280 sensor)
    //String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14";

    // Send HTTP POST request
    int httpResponseCode = http.POST(httpRequestData);
     
    // If you need an HTTP request with a content type: text/plain
    //http.addHeader("Content-Type", "text/plain");
    //int httpResponseCode = http.POST("Hello, World!");
    
    // If you need an HTTP request with a content type: application/json, use the following:
    //http.addHeader("Content-Type", "application/json");
    //int httpResponseCode = http.POST("{\"value1\":\"19\",\"value2\":\"67\",\"value3\":\"78\"}");
        
    if (httpResponseCode>0) {
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
    }
    else {
      Serial.print("Error code: ");
      Serial.println(httpResponseCode);
    }
    // Free resources
    http.end();
  }
  else {
    Serial.println("WiFi Disconnected");
  }
  //Send an HTTP POST request every 30 seconds
  delay(30000);  
}

View raw code

Setting your network credentials

You need to modify the following lines with your network credentials: SSID and password. The code is well commented on where you should make the changes.

// Replace with your network credentials
const char* ssid     = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Setting your serverName

You also need to type your domain name, so the ESP publishes the readings to your own server.

const char* serverName = "http://example-domain.com/post-esp-data.php";

Now, you can upload the code to your board. It should work straight away both in the ESP32 or ESP8266 board. If you want to learn how the code works, read the next section.

How the code works

This project is already quite long, so we won’t cover in detail how the code works, but here’s a quick summary:

  • Import all the libraries to make it work (it will import either the ESP32 or ESP8266 libraries based on the selected board in your Arduino IDE)
  • Set variables that you might want to change (apiKeyValue, sensorName, sensorLocation)
  • The apiKeyValue is just a random string that you can modify. It’s used for security reasons, so only anyone that knows your API key can publish data to your database
  • Initialize the serial communication for debugging purposes
  • Establish a Wi-Fi connection with your router
  • Initialize the BME280 to get readings

Then, in the loop() is where you actually make the HTTP POST request every 30 seconds with the latest BME280 readings:

// Your Domain name with URL path or IP address with path
http.begin(client, serverName);

// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");

// Prepare your HTTP POST request data
String httpRequestData = "api_key=" + apiKeyValue + "&sensor=" + sensorName                      + "&location=" + sensorLocation + "&value1=" + String(bme.readTemperature())                      + "&value2=" + String(bme.readHumidity()) + "&value3=" + String(bme.readPressure()/100.0F) + "";

int httpResponseCode = http.POST(httpRequestData);

You can comment the httpRequestData variable above that concatenates all the BME280 readings and use the httpRequestData variable below for testing purposes:

String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14";

Demonstration

After completing all the steps, let your ESP board collect some readings and publish them to your server.

Cara menggunakan connect php to firebase

If everything is correct, this is what you should see in your Arduino IDE Serial Monitor:

Cara menggunakan connect php to firebase

If you open your domain name in this URL path:

http://example-domain.com/esp-data.php

You should see the all the readings stored in your database. Refresh the web page to see the latest readings:

Cara menggunakan connect php to firebase

You can also go to phpMyAdmin to manage the data stored in your SensorData table. You can delete it, edit, etc…

Cara menggunakan connect php to firebase

Wrapping Up

In this tutorial you’ve learned how to publish sensor data into a database in your own server domain that you can access from anywhere in the world. This requires that you have your own server and domain name (you can use a Raspberry Pi for local access).

The example provided is as simple as possible so that you can understand how everything works. After understanding this example, you may change the appearance of the table, publish different sensor readings, publish from multiple ESP boards, and much more.

You might also like reading:

  • [Course] Learn ESP32 with Arduino IDE
  • ESP32 Publish Sensor Readings to Google Sheets (ESP8266 Compatible)
  • ESP32 Bluetooth Classic with Arduino IDE – Getting Started
  • ESP32 Web Server with Arduino IDE

I hope you liked this project. If you have any questions, post a comment below and we’ll try to get back to you.

If you like ESP32, you might consider enrolling in our course “Learn ESP32 with Arduino IDE“. You can also access our free ESP32 resources here.

Thank you for reading.

Apakah Firebase menggunakan api?

Firebase menyediakan library untuk berbagai client platform. Kita tinggal pakai saja. Browser pakai Javascript API dan mobile pakai OBJ-C atau Android API. Bagi web developer sangat memungkinkan untuk membuat aplikasi "Only HTML Css Js" karena sisi server dan database sudah dihandle oleh Firebase.

Apakah Firebase termasuk cloud?

Firebase Realtime Database adalah database NoSQL yang di-hosting di cloud dan dapat digunakan untuk menyimpan dan menyinkronkan data antarpengguna secara real time.

Mengapa Firebase Realtime Database tetap responsif bahkan saat offline?

Kemampuan lain dari Firebase Realtime Database adalah tetap responsif bahkan saat offline karena SDK Firebase Realtime Database menyimpan data langsung ke disk device atau memori lokal. Setelah perangkat terhubung kembali dengan internet, perangkat pengguna (user) akan menerima setiap perubahan yang terjadi.

Jelaskan apa yang dimaksud dengan Firebase Realtime Database?

Definisi lain dari Firebase adalah platform dari Google yang menyediakan berbagai layanan untuk memudahkan pengembangan aplikasi web, Android, iOS, maupun Unity. Platform ini mampu mempermudah dalam pengembangan aplikasi bersifat Realtime Database.