Database stored on ESP8266

I need to make simple database on site with data stored on flash of ESP8266. I know that I need to use Fetch command but I am not sure how exactly should I implement it. Bellow you can find code that I have came up with using chat GPT and some inernet forums.

CSS one:


#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include "webpageCode.h"

const int length = 15;

int index_user=0;
typedef struct {
  String name;
  String id;
} user;
user users[15]; // String array to hold user input
int userCount = 0; // Variable to keep track of the number of users

ESP8266WebServer server(80);
const int builtInLedPin = 2; // Assuming LED_BUILTIN is defined as 2, change if necessary
void setup() {
  Serial.begin(115200);

  // Replace with your network credentials
  const char* ssid = "GalaxyA526AF7";
  const char* password = "12345678";

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  // Start the server
  server.on("/", handleRoot);
  server.begin();
  Serial.println("HTTP server started");

  // Set built-in LED pin as output
  pinMode(builtInLedPin, OUTPUT);
  
  // Initially turn off the built-in LED
  switchOffBuiltInLed();
}

void loop() {
  server.handleClient();
}



// Function to handle root URL
void handleRoot() {
  if (server.arg("led") == "0") {
    switchOnBuiltInLed();
  } else if (server.arg("led") == "1") {
    switchOffBuiltInLed();
  }
  if (server.arg("user").length()>0) {
    String temp = server.arg("user");
    String temp2 = server.arg("id");
    if(index_user<length){
      users[index_user].name=temp;
      users[index_user].id=temp2;
      index_user+=1;
      for( int i=0;i<index_user;i++){
        Serial.print(users[i].name);
        Serial.print(";");
        Serial.print(users[i].id);
        Serial.println(";   ");
      }
      
    }
    else{
      Serial.println("Max users");
    }
  }

  server.send(200, "text/html", webpageCode);
}

// Function to switch on the built-in LED
void switchOnBuiltInLed() {
  digitalWrite(builtInLedPin, LOW); // Built-in LED is active low, so LOW turns it on
}

// Function to switch off the built-in LED
void switchOffBuiltInLed() {
  digitalWrite(builtInLedPin, HIGH); // Built-in LED is active low, so HIGH turns it off
}

HTML one:


#ifndef WEBPAGE_CODE_H
#define WEBPAGE_CODE_H

const char webpageCode[] PROGMEM = R"=====(
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ESP8266 Webpage (Diode controller and Userbase)</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            margin: 0;
            padding: 0;
        }
        .container {
            max-width: 600px;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
            margin-bottom: 20px;
        }
        .btn {
            display: inline-block;
            padding: 10px 20px;
            margin: 0 10px 10px 0;
            background-color: #4CAF50;
            color: white;
            text-decoration: none;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        .btn:last-child {
            margin-right: 0;
        }
        .user-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        .user-table th, .user-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        .input-field {
            width: calc(100% - 20px);
            padding: 10px;
            border-radius: 5px;
            border: 1px solid #ccc;
            margin-bottom: 10px;
        }
        .add-user-btn {
            width: calc(100% - 20px);
            padding: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>ESP8266 Webpage (Diode controller and Userbase)</h1>
        <div>
            <a href="?led=0" class="btn">Turn LED ON</a>
            <a href="?led=1" class="btn">Turn LED OFF</a>
        </div>
        
        <!-- User Table -->
        <table class="user-table">
            <thead>
                <tr>
                    <th>User ID</th>
                    <th>Username</th>
                </tr>
            </thead>
            <tbody>
                <!-- User data will be dynamically populated here -->
            </tbody>
        </table>

        <!-- Add User Form -->
        <input type="text" class="input-field" placeholder="Enter Username" id="usernameInput">
        <button class="add-user-btn" onclick="addUser()">Add User</button>
    </div>

    <script>
        // Function to add user to the table
        function addUser() {
            let username = document.getElementById('usernameInput').value;
            if (username.trim() !== '') {
                let tbody = document.querySelector('.user-table tbody');
                let newRow = document.createElement('tr');
                let userID=generateUserID();
                newRow.innerHTML = '<td>' + userID + '</td><td>' + username + '</td>';
                tbody.appendChild(newRow);
                // Clear input field after adding user
                document.getElementById('usernameInput').value = '';
                fetch('/?user=' + username+'&id='+userID);
            } else {
                alert('Please enter a username.');
            }
        }

        // Function to generate a random user ID
        function generateUserID() {
            return Math.random().toString(36).substr(2, 9);
        }
    </script>
</body>
</html>
)=====";

#endif


How many records will the database need to store, where do the data come from, through which process(es) do the records get updated, and how will the data be used?

Just simple datbase to hold up to 15 users with their uniqe IDs. Data will be input on the site. Data will be used to create RFID profiles on cards.

I believe that you need to include the SPIFFS library.

What exactly will be stored of each user?

Which site(s)?
How/when will user files be deleted? How/when are they updated?

Where does this RFID profile creation take place? How does the ESP interface with this process?

use Preferences.h (by author=Volodymyr Shymanskyy)
it's no database, more like writing/reading to a .ini file.
for 15 entities just right on the ESP.

  1. right now IDs and their nicknames/names but later I will add function to assign RFIDs to them.

  2. Local site hosted on EPS

  3. All will be done on that site

I need to save them on ESP as they must be accessible even after powering down ESP

Well, I'd suggest the simplest approach; a single file in SPIFFS, comma separated values, line break denotes next record. Especially if you only expect a couple dozen users, this should work just fine.

Good I'll try this thx

please read it again. preferences will store the values on the ESP. Access to the data will be far easier and structured than in a single file. Preferences will come with all functions to read and write the values.

1 Like

even after device is powered down? I need it to be able to recoginze users even after powerloss/powerdown

Yup; I've never used it, but it does pretty much what OP wants.

Yes. See e.g. here: ESP32 Save Data Permanently using Preferences Library | Random Nerd Tutorials

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.