Question about uploading data to local database

Hello.

I'm currently working on some project. First i made a sketch which measure the temperature (sensor is LM35). Then i made some PHP files where i made a database and some test inserts into table on localhost. Now i was wondering if is it possible to make an Arduino sketch, which will contain a sketch to mesaure Temperature and then to upload it to my database. It will only need to get 2 data's (temperature, and current date (TIMESTAMP in mySql).

So long i have made this which (Koncna_2):

#include <Bridge.h>
#include <SPI.h>
#include <BridgeClient.h>
#include <Ethernet.h>

const char *server = "127.0.0.1";
const char *tabela = "PodatkiYun";

float temp;
int tempPin = 0;

BridgeClient client;
char buffer(64);


void setup() {
  // put your setup code here, to run once:
  Bridge.begin();
}

void loop() {
  // put your main code here, to run repeatedly:
  temp = analogRead(tempPin);
  temp = temp * 0.48828125;
    Serial.println("\nconnecting  ");
  if (client.connect(server, 80)){
    Serial.print("sending ");
 //   sprintf(buffer, "POST /php2/Vnosi.php HTTP/1.1");
    client.println(buffer);
    Serial.println(buffer);
//    sprintf(buffer, "Host: %s", server);
    client.println(buffer);
    Serial.println(buffer);
    //JSON content
    client.println("Content-Type: application/json");
    Serial.println("Content-Type: application/json");
    // POST body
    sprintf(buffer, "( temperatura : temp, datum: date('Y-m-d-h-i-s'))");
    client.print("Content-Length: ");
    Serial.print("Content-Length: ");
    client.println();
    Serial.println();
    client.println(buffer);
    Serial.println(buffer);
  } else{
  Serial.println("Povezava ni uspela");
}

  
}

Because i can't upload PHP files here is a link to them:

Create DB: Create DB - Pastebin.com
Create Table: Create Table - Pastebin.com
Check the table: Check the table - Pastebin.com
Insert into table: Insert data - Pastebin.com

Greetings and thanks for help

Jure

Temperatura_pravi.ino (548 Bytes)

I'm sure you can get this to work this way, but it's a very inefficient and overly complicated solution. In essence, this code is using the Bridge Library to send commands to the Linux side to open a TCP socket with the local web server. It is then manually sending the HTTP commands to post the data, which is being sent to the Linux side which then forwards it to the web server, which then forwards it to PHP, which then sends it to the database. That's a lot of extra overhead there.

A much simpler solution is to use the Process class to call a Linux script directly. That script then receives the data and puts it in the database. If you can rework your PHP code to take input from the command line rather than a web service, you could call the script directly with a Process class object.

It's been a long time since I did anything with MySQL, but Isn't there is a command line tool that you can run from the Linux command prompt to manage the database and insert data? If so, you might be able to call that directly from the Process object in the sketch and not have to write a Linux script?

Jure,

I honestly don't follow all of the JSON things you are doing right now, but this is how I get data from my Arduino to the MySQL DB:

This function calls my php script and than adds each variable I want to upload as a Parameter.
You have to have php-cli and php installed.

void dbcpinsert() { //inserts readings from stations 1,2,3,4 into the DB
  Process insert; //this sends information on stations 1 and 2 to the db
  insert.begin("php-cli");
  insert.addParameter("/mnt/sda1/db_cpwrite.php");
  insert.addParameter(String(timestamps[0]));  //insert timestamp for these readings
  insert.addParameter(String(readings[0]));  //insert reading from station 1
  insert.addParameter(String(readings[1]));  //insert reading from station 2
  insert.addParameter(String(Setting));
  insert.addParameter(String(readings[2]));  //update reading from station 3
  insert.addParameter(String(readings[3]));  //update reading from station 4
  insert.addParameter(String(timestamps[offset])); //SQL will update the row matching this timestamp
  insert.run();
}

[db_cpwrite.php]
This receives each of the arguements from the arduino and assigns a variable name to each.
I actually run two MySQL queries in this script (one INSERT and one UPDATE).

#!/usr/bin/php-cli
<?php
$var1 = $argv[1];  //timestamp for station 1 and 2
$var2 = $argv[2];  //station 1
$var3 = $argv[3];  //station 2
$var4 = $argv[4];  //adjustmentdial
$var5 = $argv[5];  //station 3
$var6 = $argv[6];  //station 4
$var7 = $argv[7];  //timestamp for station 3 and 4


$DBServer = '127.0.0.1'; 
$DBUser   = 'root';
$DBPass   = 'xxxxxxxxxxxxxxxxxxx';
$DBName   = 'yun';  
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
// check connection
if ($conn->connect_error) {
  trigger_error('Database connection failed: '  . $conn->connect_error, E_USER_ERROR);
}
$sql="INSERT INTO assy5cp (timestamp, station1, station2, adjustmentdial) VALUES ($var1,$var2,$var3,$var4);
UPDATE assy5cp SET station3=$var5, station4=$var6 WHERE timestamp=$var7;";
if($conn->multi_query($sql) === false) {
  trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} 
?>

I read info back from the database like this:
The function requests data back from MySQL, which is than read much like you would a serial input. In this case I populate an array with the values.

void dbcpreadstats() {
  String result; //creates a result string
  char c; //creats a char
  Process readstats; //
  readstats.begin("php-cli");
  readstats.addParameter("/mnt/sda1/db_cpreadstats.php");
  readstats.run();
  for (int d = 0; d < 15; d++) {
    result = "";
    c = 1;
    while (readstats.available() > 0 && c != '\n') {
      c = readstats.read();
      if (isDigit(c)) result += c;
    }
    avgarray[d] = result.toInt();
  }
}

[db_cpreadstats.php]
This sends a SELECT query to MySQL and prints the data back to the Arduino.

#!/usr/bin/php-cli
<?php

$DBServer = '127.0.0.1'; 
$DBUser   = 'root';
$DBPass   = 'xxxxxxxxxxxxxxxxxxxxx';
$DBName   = 'yun';  
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
// check connection
if ($conn->connect_error) {
  trigger_error('Database connection failed: '  . $conn->connect_error, E_USER_ERROR);
}
$query = "SELECT data FROM assy5cp_stats;";
$result = $conn->query($query);
if($result === false) {
  trigger_error('Wrong SQL: ' . $query . ' Error: ' . $conn->error, E_USER_ERROR);
}
$result->data_seek(0);

    while ($row = mysqli_fetch_row($result)) {

		printf ("%s \n", $row[0]);
    }



$result->free();
$conn->close();
?>

Let me know if you have any questions on this methodology.

I create my databases and tables from a windows application (HeidiSQL) rather than from the command line, FYI.

First of all i would like to thank you for replies

@ShapeShifter : Yeah, first i thought it would be the easiest way to do that project just by making a php files and then use it in Arduino, but then it figures out that that isn't the easiest way, so thanks for the tip i will check it out, and then hope to know hot to write that code ^^

@DarkSabre: Yeah those JSON things were just sometning i tried, but it didn't work (at least not in arduino sketch).

So let me check if i get your code right. First code you have in your Arduino sketche, in which you insert data you get from arduino (reading) to your database. In 2nd code i was just wondering from which array you choose datas (here: $var1 = $argv[1]:wink: . In code 3 if i get i right, you made a process then you add some datas to your datababse? I just don't get if clasue though...

I'm just wondering does your project does this automactly. Because i need this project to be automatic, so nobody doesn't need to be around when arduino is turned on...

Hope it makes sense what i wan't to ask, cause english is not my primary language and i'm just working on arduino for only a few days

Thanks in advance!

Jure199:
@ShapeShifter : Yeah, first i thought it would be the easiest way to do that project just by making a php files and then use it in Arduino

Well, it is a relatively easy way, it's just not a particularly efficient way. It's the same situation as many of the Arduino examples: it's easy, but not necessarily the best way to do it (especially once it grows in scope beyond a simple example project.)

DarkSabre's code is exactly what I was trying to describe: use a Process object in the script to call a Linux script to do the actual work. In DarkSabre's example, he's using a PHP script and running it by calling the PHP command line interpreter directly. In essence, it's cutting out all of the networking, HTTP, and web server overhead out of the loop, and sending the data directly to PHP.

So let me check if i get your code right. First code you have in your Arduino sketche, in which you insert data you get from arduino (reading) to your database. In 2nd code i was just wondering from which array you choose datas (here: $var1 = $argv[1]:wink: .

Yes, the first piece of code is in the sketch. It creates a process object, and tells it to run php-cli, the PHP interpreter. It then adds a bunch of parameters: the first is the name of the PHP script, and the subsequent parameters are the values being passed to the script.

The second piece of code is the PHP script. The $argv array contains the command line parameters. $argv[0] will have the name of the script file (which is not necessarily useful, so it is ignored.) $argv[1] contains the first argument, $argv[2] contains the second, and so on. Each one of these are copied to a local variable inside the PHP script. Make sure you understand what is going here, as it is the key to making this work in your own situation. Following the data from the sketch (listing 1) to the local variables in the PHP script (listing 2) you will end up with:

  • $var1 will have timestamps[[0]
  • $var2 will have readings[0]
  • $var3 will have readings[1]
  • $var4 will have Setting
  • $var5 will have readings[2]
  • $var6 will have readings[3]
  • $var7 will have timestamps[offset]

In code 3 if i get i right, you made a process then you add some datas to your datababse? I just don't get if clasue though...

The third bit of code is a part of the sketch which reads some data back out of the database. The fourth bit of code is the corresponding PHP script.

Starting with the PHP script, it connects to the database and makes a query. It then loops through each returned row, and prints out the first field from each row. Each value is printed as a number, followed by a space, and then a new line. If you were to run this from the command line, you would see each value printed to the screen on a new line.

Now, back to the third bit of code. This runs in the sketch. It once again creates a Process object to run the php_cli command interpreter. The only parameter this time is the name of the PHP script that is the fourth piece of code. The Process is then run. Now, any output from the PHP script (the values printed in the loop at the end of the script) can be read from the Process object. In this case, the code is expecting up to15 lines of data.

In that code, readstats is the Process object. It can be read in exactly the same way as a serial port: the .available() function returns how many characters are waiting to be read, while the .read() function returns the next character. The loop starts by clearing the result String, and then loops as long as there is still data, and the newline character has not been read. Inside of that loop, it reads the next character, and if it is a numeric digit, it adds it to the result string. In this way, it is combining all of the digits for one line of the response into a String. Once it drops out of the while loop (either because there is no more data, or it read the end of a line) the current result String is converted to an integer, assigned to a result array, and the for loop repeats to process the next line.

I'm just wondering does your project does this automactly. Because i need this project to be automatic, so nobody doesn't need to be around when arduino is turned on...

Yes, it is automatic, all controlled by the sketch. The code in the first block is a self-contained function() (which is a good way to organize it.) Whenever that function is called from the sketch, the PHP script will be run on the Linux side, and the database will be updated.

Not mentioned in that code are the additional steps you will need to take: your sketch must include Bridge.h and Process.h, and you must call Bridge.begin() in your setup() function - just as you do in your existing sketch.

In code #4, I'm requesting data from the MySQL server. To give you an idea of what the Arduino is receiving, see below.

If I run this at the linux commandline (via PuTTy/SSH)

/usr/bin/php-cli /mnt/sda1/db_cpreadstats.php

I get this:

85
90
90
90
89
86
83
87
2543
6158
2015
3033

As ShapeShifter noted, Code #3 recieves this information into the serial buffer and starts parsing through it.

Depending on what kind of data you are retrieving, this section of code might need to change, as it is designed to receive data that fits into the Integer size:

  for (int d = 0; d < 15; d++) {          //loops through checking for up to 15 entries, you would only need to check for 2 entries
    result = "";
    c = 1;  //this resets the last stored character to a 1 (in what I've done here, this is needed because the while loop won't run if a newline character is present)
    while (readstats.available() > 0 && c != '\n') {    //checks to make sure that serial information is availible and that the last character read was not a new line character
      c = readstats.read();  //reads a new character
      if (isDigit(c)) result += c;   //if that character was a digit, add it to the string
    }
    avgarray[d] = result.toInt();   //once a newline character has been hit, the while loop exits and this turns the string into an integer
  }

^I added some additional comments to help you make sense of it.

My guess is that for you:
-Temperature is going to be a Float (decimal) value
-Timestamp is going to be either a String or a Long Int

This means that the the exact code I have for parsing the data from the MySQL command won't work for you, since I'm working only with INT values.

You might try something like the below code. Since you only have to retrieve 2 variables, it probably isn't worth making a for loop and using an array.

void dbcpreadstats() {
  String result; //creates a result string
  char c; //creats a char
  Process readstats; //
  readstats.begin("php-cli");
  readstats.addParameter("/mnt/sda1/db_cpreadstats.php");
  readstats.run();
  while (readstats.available() > 0 && c != '\n') {   //read the values and add them to a string for the temperature until you hit a newline character
      c = 1; //reset c
      if (c!='\n') temperaturestring += c;
  }
  c = readstats.read();
  while (readstats.available() > 0 && c != '\n') {   //read the values and add them to a string for the timestamp until you hit a newline character
      c = readstats.read();
      if (c!='\n') timestampstring += c;
  }
}

Not the most elegant way, but I imagine that would work.

I forgot to mention one of the software packages:

php5
php5-cli
php5-mod-mysqli

Thank you very much for the answers. First i need to apologize for late answer, but in the weekend i can't get to arduino, because i can't take it home from my practice in the job. :(. And yesterday i was still sick and wasn't attending job.

@ShapeShifter: Yeah i figure it out that it's like the examples. I'm relativly new with arduino so i might have asked some stupid questions. I will try to get over that code (from DarkSabre) from wednesday (tommorow) till friday and i hope i will manage to get it right . Today i needed to do some other work on excel and word so i didn't have time for my arduino project Thanks for analyzing the code for me. I think i could manage to get it through later on this week.

@DarkSabre: Ok i have installed PuTTy today, and if i get it correctly i need to run this code (of course with different line of path to my database) and then i should get timestamp and value. Thanks for some additional comments in the code. Yeah temperature is gonna be Float, and Timestamp will probably gonna be String. I was also think the same way that i wouldn't need for loop cause i only have 2 variables. Btw can i work with windows 7 OS, or i need to get Linux to get install php-chi and php5-mod-mysqli ?

So to conclude. I will try this code tommorow and if i will have any other questions i will ask here. Thanks again for your help

Greetings Jure

Jure,

The 3 software packages (php5, php5-cli, php5-mod-mysqli) actually need to be installed on the linux side of your Yun. You can do that either through the web interface (log into Yun --> advanced control panel --> System --> Software) or on the command line with something like putty using the opkg package manager:

root@Assy5CPYun:~# opkg update
Downloading http://download.linino.org/linino_distro/lininoIO/latest/packages/Packages.gz.
Updated list of available packages in /var/opkg-lists/attitude_adjustment.
Downloading http://download.linino.org/linino_distro/lininoIO/latest/packages/Packages.sig.
Signature check passed.
root@Assy5CPYun:~# opkg install php5
Package php5 (5.6.13-1) installed in root is up to date.

etc

For simple packages like these I just use the web interface.

The software packages install the php5 language, a command line interpreter, and some extra functionality for working with mysql.

But yes, you can use PuTTY to make sure that the php script you've written works properly and to understand the kind of output your php script gives so that you can properly program the Arduino to deal with that output.

DarkSabre:
But yes, you can use PuTTY to make sure that the php script you've written works properly and to understand the kind of output your php script gives so that you can properly program the Arduino to deal with that output.

This is very good advice! Definitely test the Lnux side scripts at the command line using PuTTY. Make sure they are processing the data correctly, and generating the right output. Only after you are sure they are working correctly should you consider trying to call them from the sketch using the Process object. This will make things much easier - if the Linux side scripts are not working, running them through a Process object will not magically make them work - it will only make it more difficult to debug.

DarkSabre:
Jure,

The 3 software packages (php5, php5-cli, php5-mod-mysqli) actually need to be installed on the linux side of your Yun. You can do that either through the web interface (log into Yun --> advanced control panel --> System --> Software) or on the command line with something like putty using the opkg package manager:

But yes, you can use PuTTY to make sure that the php script you've written works properly and to understand the kind of output your php script gives so that you can properly program the Arduino to deal with that output.

Thanks for the tip, i really didn't know that you need to download files to arduino (i used web interface aswell). And yes i will use PuTTY to check if the program is running correctly

Thank you again!

Ok i have installed those addititonal software packages to arduino. Now i still have problems.

First i was wondering if this path is correct to my database

  Process readstats; //
  readstats.begin("php-cli");
  readstats.addParameter("localhost/php22/Vnosi.php");

or is it something else. (IP of localhost is 127.0.0.1).

2nd. I was wondering where in the code should i put this code

reading = analogRead(tempPin);
tempC = reading / 9.31;
Serial.println(tempC);
delay(1000);

I think that it should be inside void loop.

3rd I have decided to work with your PHP's now. I would like you to check if they are correct. [db_cpreadstats.php]

#!/usr/bin/php-cli
<?php

$DBServer = '127.0.0.1'; 
$DBUser   = 'YUN';
$DBPass   = 'xxx';
$DBName   = 'TestnaBaza';  
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
// check connection
if ($conn->connect_error) {
  trigger_error('Database connection failed: '  . $conn->connect_error, E_USER_ERROR);
}
$query = "SELECT data FROM YunPodatki;";
$result = $conn->query($query);
if($result === false) {
  trigger_error('Wrong SQL: ' . $query . ' Error: ' . $conn->error, E_USER_ERROR);
}
$result->data_seek(0);

    while ($row = mysqli_fetch_row($result)) {

		printf ("%s \n", $row[0]);
    }



$result->free();
$conn->close();
?>

and then [db_cpwrite.php]

#!/usr/bin/php-cli
<?php
$var1 = $argv[1];  //Temperature
$var2 = date('Y-m-d-h-i-s') ;  //Timestamp



$DBServer = '127.0.0.1'; 
$DBUser   = 'YUN';
$DBPass   = 'xxx';
$DBName   = 'TestnaBaza';  
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
// check connection
if ($conn->connect_error) {
  trigger_error('Database connection failed: '  . $conn->connect_error, E_USER_ERROR);
}
$sql="INSERT INTO YunPodatki (temperatura, datum) VALUES ($var1,$var2)";

if($conn->multi_query($sql) === false) {
  trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} 
?>

And here i have a question. How can this $argv[1] become a variable called tempC from my code to get reading from temperature sensor.

And lastly i have a question of how to modify this arduino sketch to sucesfully connect and work with my database on localhost.

#include <Process.h>
#include <Bridge.h>
#include <Ethernet.h>

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};

IPAddress ip(192, 168, xx, xxx); //IP address of the computer
char server[] = "192.168.xx.xxx"; // IP address of the Arduino

int intPin = 0; //
int reading = 0; //What it's gonna read...
String temperaturestring = "";
String timestampstring = "";

EthernetClient client,

void setup() {
  Bridge.begin();
  //Ethernet.begin(mac,ip);
}

void loop() {

  reading = analogRead(tempPin);
  tempC = reading / 9.31;
  Serial.println(tempC);
  delay(1000);
  reading = analogRead(intPin) // preberemo
            // povezemo na server
}

void dbcpreadstats() {
  String result; //creates a result string
  char c; //creats a char
  Process readstats; //
  readstats.begin("php-cli");
  readstats.addParameter("localhost/php22/db_cpreadstats.php");
  readstats.run();
  while (readstats.available() > 0 && c != '\n') {   //read the values and add them to a string for the temperature until you hit a newline character
    c = 1; //reset c
    if (c != '\n') temperaturestring += c;
  }
  c = readstats.read();
  while (readstats.available() > 0 && c != '\n') {   //read the values and add them to a string for the timestamp until you hit a newline character
    c = readstats.read();
    if (c != '\n') timestampstring += c;
  }
}

Thanks for the help!

Jure

I made this table to test out the Write code

CREATE TABLE `YunPodatki` (
 `temperatura` FLOAT NULL DEFAULT NULL,
 `datum` DATETIME NULL DEFAULT NULL
)
ENGINE=InnoDB;

I get this error when I run the php script in putty. Maybe your timezone thing works, but it failed for me.

root@Assy5CPYun:~# php-cli /mnt/sda1/Test.php 13.52

Warning: date(): It is not safe to rely on the system's timezone settings. You a               re *required* to use the date.timezone setting or the date_default_timezone_set(               ) function. In case you used any of those methods and you are still getting this                warning, you most likely misspelled the timezone identifier. We selected the ti               mezone 'UTC' for now, but please set date.timezone to select your timezone. in /               mnt/sda1/Test.php on line 4

Fatal error: date(): Timezone database is corrupt - this should *never* happen!                in /mnt/sda1/Test.php on line 4

If I take the timestamp out of the code and let the database generate it automatically:

CREATE TABLE `yunpodatki` (
 `temperatura` FLOAT NULL DEFAULT NULL,
 `datum` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY (`datum`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB;

^datum is now the primary key and automatically populates with the current timestamp when a row is added.

#!/usr/bin/php-cli
<?php
$var1 = $argv[1];  //Temperature

$DBServer = 'xxxxxxxxxxxx'; 
$DBUser   = 'xxxxxxxxxx';
$DBPass   = 'xxxxxxxxxxxx';
$DBName   = 'xxxxxxxxxxx';   
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
// check connection
if ($conn->connect_error) {
  trigger_error('Database connection failed: '  . $conn->connect_error, E_USER_ERROR);
}
$sql="INSERT INTO YunPodatki (temperatura) VALUES ($var1)";

if($conn->multi_query($sql) === false) {
  trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} 
?>

Then this is what I get in Putty

root@Assy5CPYun:~# php-cli /mnt/sda1/Test.php 13.52
root@Assy5CPYun:~# php-cli /mnt/sda1/Test.php 13.55
root@Assy5CPYun:~# php-cli /mnt/sda1/Test.php 13.56

^no feedback = no errors

and this is what the database shows:

13.52	2016-06-02 10:33:01
13.55	2016-06-02 10:33:23
13.56	2016-06-02 10:33:31

As written, I get this error on the Reading code:

root@Assy5CPYun:~# php-cli /mnt/sda1/TestReturn.php

Fatal error: Wrong SQL: SELECT data FROM YunPodatki; Error: Unknown column 'data' in 'field list' in /mnt/sda1/TestReturn.php on line 16

because I don't have a column named data in my database. If you do, this would work.

Just to show that, I changed "data" to "temperatura"

"$query = "SELECT temperatura FROM YunPodatki;";"

And this is what I get in Putty:

root@Assy5CPYun:~# php-cli /mnt/sda1/TestReturn.php
13.52
13.55
13.56

So that's how I'd make the PHP/SQL side of things work.
I'll try to respond to the arduino implementation side later, if someone else doesn't beat me to it.

To your first question:
-You are asking about the path to your database, but showing the path to a php file.

I don't think you really mean the database location, but that is controlled by the configuration file located here:
/etc/my.conf

There will be an entry for the datadir, which controls where the mysql database is located. Mine is located on my SD card in a folder called data:
datadir = /mnt/sda1/data/mysql/

If you are asking where to locate a php file to run it, I would put it on the SD card, which for me would make your entry:
readstats.addParameter("/mnt/sda1/Vnosi.php");

You might have a slightly different folder path.

To your 2nd question:
I imagine you do want that inside your main loop. You will read the temp data from the sensor and then store it into the database. So call the function that writes to the database each time after you read a value from the sensor.

To your question about passing the temp reading to $argv[1]:
$argv[1] is going to equal the next addParameter after your php script, so:

void dbcpinsert() {
  Process insert;
  insert.begin("php-cli");
  insert.addParameter("/mnt/sda1/db_cpwrite.php");
  insert.addParameter(String(tempC));  //insert the temperature, the php script will take this as $argv[1]
  insert.run();
}

or whatever the equivalent is for your php script's name

Hey well now i have changed some php scripts. It worked before and it works now, but now it's only 1 variable which is better. So here are the codes
[db_cpwrite.php]

#!/usr/bin/php-cli
<?php
$var1 = $argv[1];  //Temperature
//$var2 = date('Y-m-d-h-i-s') ;  //Timestamp



$DBServer = '127.0.0.1'; 
$DBUser   = 'YUN';
$DBPass   = 'xxx';
$DBName   = 'TestnaBaza';  
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
// check connection
if ($conn->connect_error) {
  trigger_error('Database connection failed: '  . $conn->connect_error, E_USER_ERROR);
}
$sql="INSERT INTO YunPodatki (temperatura) VALUES ($var1)";

if($conn->multi_query($sql) === false) {
  trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} 
?>

This works if I insert manually value, but still when it connects with arduino somehow it doesn't work.

The 2nd code is
[db_cpreadstats.php]

#!/usr/bin/php-cli
<?php

$DBServer = '127.0.0.1'; 
$DBUser   = 'YUN';
$DBPass   = 'xxx';
$DBName   = 'TestnaBaza';  
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
// check connection
if ($conn->connect_error) {
  trigger_error('Database connection failed: '  . $conn->connect_error, E_USER_ERROR);
}
$query = "SELECT * FROM YunPodatki;";
$result = $conn->query($query);
if($result === false) {
  trigger_error('Wrong SQL: ' . $query . ' Error: ' . $conn->error, E_USER_ERROR);
}
$result->data_seek(0);

    while ($row = mysqli_fetch_row($result)) {

		printf ("%s \n", $row[0]);
    }



$result->free();
$conn->close();
?>

But when i run this sketch. It doesn't work / update data to my database. I really have no idea why this isn't working.

#include <Process.h>
#include <Bridge.h>
float reading;
float tempC;
int tempPin = 0;

void setup() {
  // put your setup code here, to run once:
  Bridge.begin();
}

void loop() {
  // put your main code here, to run repeatedly:
  reading = analogRead(tempPin);
  tempC = reading / 9.31;
  tempC = 25;
  Serial.println(tempC);
  delay(1000);
}

void dbcpinsert() {
  Process insert;
  insert.begin("php-cli");
  insert.addParameter("/xampp/htdocs/php22/db_cpwrite.php");
  insert.addParameter(String(tempC));  //insert the temperature, the php script will take this as $argv[1]
  insert.run();
}

Here is the path to my database which should and is upload data to my PHPMyAdmin: Link . Like this when i press it from localhost on the internet: Link2

Thanks for the help again

Greetings

Jure

I then tried this aswell, and still it didn't work correctly. I really don't know what should i changed -.-

#include <SPI.h>
#include <Bridge.h>
#include<YunClient.h>

char server[] = "192.168.xx.xxx"; 


YunClient client;

void setup() {
  Serial.begin(9600);
  Bridge.begin();
}

void loop() {

  ////Temperature
  
  if (client.connect(server, 80)) {
    Serial.print("connected");
     client.print("GET /xampp/htdocs/php22/db_cpwrite.php"); // This
        client.print("temp="); 
        client.print(26);
        client.println(" HTTP/1.1"); // Part of the GET request
        client.println("Host: 192.168.xx.xxx"); 
        client.println("Connection: close"); // Part of the GET request telling the server that we are over transmitting the message
        client.println(); // Empty line
        client.println(); // Empty line
        client.stop();    // Closing connection to server
  }
  else {
 //  If Arduino can't connect to the server (your computer or web page)
    Serial.println("--> connection failed\n");
  }
 }

void loop() {
// put your main code here, to run repeatedly:
reading = analogRead(tempPin);
tempC = reading / 9.31;
tempC = 25;
Serial.println(tempC);
dbcpinsert(); //you need to call the insert function, otherwise it won't occur
delay(1000);
}

With this line and your screenshots:
insert.addParameter("/xampp/htdocs/php22/db_cpwrite.php");
it looks like the php file is located on your computer instead of on the Yun itself. This might work, but I don't have a way to test it like that myself.

With the php script located on the Yun's SD card and with the above change to the script to call the insert function, your sketch does successfully update the database (see attached database image).

Thanks for help. I will get SD card today and i will install it tommorow. But i think it will work beacause we have same code.

#include <Process.h>
#include <Bridge.h>
float reading;
float tempC;
int tempPin = 0;
void setup() {
  // put your setup code here, to run once:
  Bridge.begin();
}

void loop() {
  // put your main code here, to run repeatedly:
  reading = analogRead(tempPin);
  tempC = reading / 9.31;
  test value tempC = 25; // test value
  Serial.println(tempC);
  dbcpinsert();
  delay(1000);
}

void dbcpinsert() {
  Process insert;
  insert.begin("php-cli");
  insert.addParameter("localhost/php22/db_cpwrite.php"); // Will change tommorow to SD card folder
  insert.addParameter(String(tempC));  //insert the temperature, the php script will take this as $argv[1]
  insert.run();
}

Thanks for all the help both of you!

Jure