-->
Page 1 of 1

ESP8266 call URL to post data to database

PostPosted: Wed Nov 29, 2017 8:50 am
by bramulous
Hi everyone! New here.

Somehow I can't wrap my head around the following. I've been searching and searching and couldn't find an answer. I have the following problem:

I run a database with one table. Next to that, I run a webserver, where I want to show the data in the database. I also have a NodeMCU which is connected to 4 buttons. I have to code to read out every button seperately. The idea is when you press a button, it needs to call the url of the php file on the webpage which puts the data in the database, like this:

- I press the button which says 'Tea';
- The Arduino code only simply needs to call the url as the following: "https://testwebsite.subdomain.com/write_data.php?value=Tea"
- The php file takes care of the rest, like adding 'Tea' in a column in the database.

Is there someone who can maybe help me out? Got stuck at this point for a while now. Isn't there someway just to do something like this in the code?:

Code: Select allif (buttonState != lastButtonState) {
    // if the state has changed, post to db
    if (buttonState == HIGH) {
      Serial.println("Tea");
      // a command which calls the url with "https://testwebsite.subdomain.com/write_data.php?value=Tea"
    } 
    delay(150);
  }

Re: ESP8266 call URL to post data to database

PostPosted: Fri Dec 01, 2017 5:10 am
by bramulous
I already got an answer! See code below:

Code: Select allvoid sendToDB(String drink) {
    Serial.println("Begin HTTP request");
      // URL where data should be passed to
      http.begin("http://www.example.com/write_data.php?value=" + drink);
      Serial.print("GET...");
     
      // start connection and get http code
      int httpCode = http.GET();

      if (httpCode > 0) {
       
        Serial.printf("GET... code: %d\n", httpCode);

        // Connection was succesful
        if (httpCode == HTTP_CODE_OK) {
            Serial.println("Connected");
            String payload = http.getString();
            Serial.println(payload);
        }
    } else {
        Serial.printf("GET failed, see following error: %s\n", http.errorToString(httpCode).c_str());
    }
    http.end();
}


Hope this will help others too!