Connecting arduino to a network and writing to php issues

Hi, i'm new to Arduino and i got an assignment to make the Spark Fun weatherstation read data, send it to a db, and show the values with a simple website.

I know arduino can't send anything directly to the database but i've been reading about using php scripts to do it.

This is what i got until now (testing with a luminosity sensor):

//libraries
#include <Ethernet.h>
#include <SPI.h>


//stuff to make the weather station work
#define uint unsigned int
#define ulong unsigned long

#define PIN_ANEMOMETER 2 //digital 2
#define PIN_VANE 5 //analog 5

//how often i want to calculate wind speed and direction
#define MSECS_CALC_WIND_SPEED 5000
#define MSECS_CALC_WIND_DIR 5000

volatile int numRevsAnemometer =0; //incremented in the interrupt
ulong nextCalcSpeed; //when it will next calc the speed
ulong nextCalcDir; //^^direction
ulong time; //millis() at each loop() start

//adc readings
#define NUMDIRS 8
ulong adc[NUMDIRS] = {26, 45, 77, 118, 161, 196, 220, 256};

//directions match 1-1
char *strVals[NUMDIRS] = {"W","NW","N","SW","NE","S","SE","E"};
byte dirOffset=0;

//config ethernet

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x97, 0xED };
IPAddress server (192,168,1,32); //i guess this needs to be the db host ip

EthernetClient client; //creates the client as an ethernetclient
int sensor = 0;      //light sensor for testing purposes
int valorSensor = 0;


//assure network conneciton
bool connected = false;



void setup(){
  Serial.begin(9600);
  pinMode(PIN_ANEMOMETER, INPUT);
  digitalWrite(PIN_ANEMOMETER, HIGH);
  attachInterrupt(0, countAnemometer, FALLING);
  nextCalcSpeed = millis() + MSECS_CALC_WIND_SPEED;
  nextCalcDir   = millis() + MSECS_CALC_WIND_DIR;
  
  //start ethernet
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to connect using DHCP");
    //ends here as there is no reason to continue
    for(;;)
    ;
  }
  else
  {
  Serial.println(Ethernet.localIP());
  }
}


void loop(void)
{ 
  if(!connected)  {
  Serial.println("not connected");
  }
  
  if (client.connect(server, 80)){
  connected = true;
  Serial.println("connected");
    
        
    //get values of the weatherstation via methods
    //this part of the code will be commented as i don't have the weatherstation in hands by now, but i would like to know if this would work
    
    //i'm hoping this works
    //calcWindDir();
    //calcWindSpeed();
    //client.print("GET /write2.php?ws=");
    //client.print(ws);
    //client.print("&&wd=");
    //client.print(strVals[x];);
    
    
    //now the part i can test right now
    int valorSensor = analogRead(sensor); //reading the luminosity sensor for testing
    Serial.print(valorSensor);
    Serial.print(" <- luminosity value");
    Serial.print("\n");
      
    client.print("GET /write.php?s=");
    client.print(valorSensor);
    Serial.print("\nit worked????????????");

    //all the needed HTML headers to ensure a good connection
    client.println(" HTTP/1.1");
    Serial.println(" HTTP/1.1");
    client.println("Host: localhost");
    Serial.println("Host: localhost");
    client.println("User-Agent: Arduino");
    Serial.println("User-Agent: Arduino");
    client.println("Accept: text/html");
    Serial.println("Accept: text/html");
    client.println("Connection: close");
    Serial.println("Connection: close");
    client.println();
    Serial.println();
     
    client.stop();
    connected = false;
    
  }
  else
  {
  Serial.println("Cannot connect to Server");         // else block if the server connection fails (debugging)
  }
  delay(500); 
}

//methods for the weatherstation

void countAnemometer() {
   numRevsAnemometer++;
}

char* calcWindDir() { //using char* as it is the type of the variable x
   int val;
   byte x, reading;

   val = analogRead(PIN_VANE);
   val >>=2;                        // Shift to 255 range
   reading = val;

   // Look the reading up in directions table. Find the first value
   // that's >= to what we got.
   for (x=0; x<NUMDIRS; x++) {
      if (adc[x] >= reading)
         break;
   }
   //Serial.println(reading, DEC);
   x = (x + dirOffset) % 8;   // Adjust for orientation
   Serial.print("  Dir: ");   
   return strVals[x];
}

int calcWindSpeed() {
   int x, iSpeed, ws;
   // This will produce mph * 10
   // (didn't calc right when done as one statement)
   long speed = 14920;
   speed *= numRevsAnemometer;
   speed /= MSECS_CALC_WIND_SPEED;
   iSpeed = speed;         // Need this for formatting below

   Serial.print("Wind speed: ");
   x = iSpeed / 10;
   Serial.print(x);
   Serial.print('.');
   x = iSpeed % 10;
   Serial.print(x);
   ws = (iSpeed/10)%10;
   
   numRevsAnemometer = 0;        // Reset counter
   return ws;
}

This is the php i got to insert files into the db

<?php
//validate that this request came from the correct/authorized IP address
$check_ip = gethostbyname('localhost'); //i guess its localhost since i'm hosting the db on my computer
//(will eventually get a dedicated server and switch the ip to the server ip)

$connect_ip = $_SERVER['REMOTE_ADDR']; //don't really understand how it works but it seems necessary
if ($check_ip <> $connect_ip) {
	die ('GTFO!'); //die as the addresses don't match
}*

$teste = $_GET['s'];


//Make the date/time for insertion
$datetime = date("Y-m-d H:i:s");

//Connect to the MySQL server
require_once ('lib/dbconfig.php');
require_once ('lib/dbconnect.php');

//The SQL stataments to insert the temperatures into the database
//Ensure that the temperature is not -127.00 indicating an invalid reading
	$sql = "INSERT INTO `test` (`teste`, `datetime`) VALUES ('$teste', '$datetime')";
	mysqli_query($conn, $sql) or die('Error, query failed. ' . mysqli_error($conn) . '
Line: '.__LINE__ .'
File: '.__FILE__);


//Close the database connection
require_once ('lib/dbclose.php');

//Mainly for testing - ensure the script finished
echo ("Done!");
?>

The php works if i put localhost/write.php?s=something in the browser url.
But when uploading the code to arduino, it shows basically every Serial.print including ones that contradict others.

serial monitor after uploading the code to arduino

I've been stuck at this for a week already and still have no idea how to fix it, when i tried to switch some of the connecting code, it just showed not connected on the serial monitor. I really need help.

trying to keep my hope up.

i've changed the code to this

//libraries
#include <Ethernet.h>
#include <SPI.h>


//stuff to make the weather station work
#define uint unsigned int
#define ulong unsigned long

#define PIN_ANEMOMETER 2 //digital 2
#define PIN_VANE 5 //analog 5

//how often i want to calculate wind speed and direction
#define MSECS_CALC_WIND_SPEED 5000
#define MSECS_CALC_WIND_DIR 5000

volatile int numRevsAnemometer =0; //incremented in the interrupt
ulong nextCalcSpeed; //when it will next calc the speed
ulong nextCalcDir; //^^direction
ulong time; //millis() at each loop() start

//adc readings
#define NUMDIRS 8
ulong adc[NUMDIRS] = {26, 45, 77, 118, 161, 196, 220, 256};

//directions match 1-1
char *strVals[NUMDIRS] = {"W","NW","N","SW","NE","S","SE","E"};
byte dirOffset=0;

//config ethernet

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x97, 0xED };
byte server[] = {insertserveriphere} ; //tested it with google ip
byte ip[] = {10, 0, 0, 177};

EthernetClient client; //creates the client as an ethernetclient
int sensor = 0;      //light sensor for testing purposes
int valorSensor = 0;


void setup(){
  Serial.begin(9600);
  pinMode(PIN_ANEMOMETER, INPUT);
  digitalWrite(PIN_ANEMOMETER, HIGH);
  attachInterrupt(0, countAnemometer, FALLING);
  nextCalcSpeed = millis() + MSECS_CALC_WIND_SPEED;
  nextCalcDir   = millis() + MSECS_CALC_WIND_DIR;
  
  //start ethernet
  Ethernet.begin(mac, ip);
  delay(1000);
  Serial.println("wait for it..");
  
  if (client.connect(server, 80)) {
    Serial.println("connected");
  }else{
    Serial.println("ops");
  }
}


void loop(void)
{   
if (client.available()){  
    //get values of the weatherstation via methods
    //this part of the code will be commented as i don't have the weatherstation in hands by now, but i would like to know if this would work
    
    //i'm hoping this works//
    //calcWindDir();
    //calcWindSpeed();
    //client.print("GET /write2.php?ws=");
    //client.print(ws);
    //client.print("&&wd=");
    //client.print(strVals[x];);
    
    
    //now the part i can test right now
    int valorSensor = analogRead(sensor); //reading the luminosity sensor for testing
    Serial.print(valorSensor);
    Serial.print(" <- luminosity value");
    Serial.print("\n");
      
    client.print("GET /write.php?s=");
    client.print(valorSensor);
    Serial.print("\nit worked????????????");

    //all the needed HTML headers to ensure a good connection
    client.println(" HTTP/1.1");
    Serial.println(" HTTP/1.1");
    client.println("Host: localhost");
    Serial.println("Host: localhost");
    client.println("User-Agent: Arduino");
    Serial.println("User-Agent: Arduino");
    client.println("Accept: text/html");
    Serial.println("Accept: text/html");
    client.println("Connection: close");
    Serial.println("Connection: close");
    client.println();
    Serial.println();

  delay(5000);
}
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }
}

//methods for the weatherstation

void countAnemometer() {
   numRevsAnemometer++;
}

char* calcWindDir() { //using char* as it is the type of the variable x
   int val;
   byte x, reading;

   val = analogRead(PIN_VANE);
   val >>=2;                        // Shift to 255 range
   reading = val;

   // Look the reading up in directions table. Find the first value
   // that's >= to what we got.
   for (x=0; x<NUMDIRS; x++) {
      if (adc[x] >= reading)
         break;
   }
   //Serial.println(reading, DEC);
   x = (x + dirOffset) % 8;   // Adjust for orientation
   Serial.print("  Dir: ");   
   return strVals[x];
}

int calcWindSpeed() {
   int x, iSpeed, ws;
   // This will produce mph * 10
   // (didn't calc right when done as one statement)
   long speed = 14920;
   speed *= numRevsAnemometer;
   speed /= MSECS_CALC_WIND_SPEED;
   iSpeed = speed;         // Need this for formatting below

   Serial.print("Wind speed: ");
   x = iSpeed / 10;
   Serial.print(x);
   Serial.print('.');
   x = iSpeed % 10;
   Serial.print(x);
   ws = (iSpeed/10)%10;
   
   numRevsAnemometer = 0;        // Reset counter
   return ws;
}

With this, i see that the arduino is not being able to connect to any server ip i put on the server[], does anyone know what i did wrong?

ulong adc[NUMDIRS] = {26, 45, 77, 118, 161, 196, 220, 256};

Why are you using a 32 bit array to hold 16 bit values?

IPAddress server (192,168,1,32); //i guess this needs to be the db host ip

No. It's the address of the server where the PHP script is. That does not have to be the same server that the database software is running. Though it usually is.

    client.println("Host: localhost");
    Serial.println("Host: localhost");

This is not necessary, unless the domain you are trying to talk to is being hosted on the same machine as many other domains.

    client.stop();

No. You make a request to the server. The server generates a response. You MUST read the entire response. When you do, the connection will close automatically, so you don't need to.

Get rid of everything you are sending to the server after the HTTP/1.1 bit.

But when uploading the code to arduino, it shows basically every Serial.print including ones that contradict others.

What parts do you think are contradictory? Initially, you are not connected to the server, so you print the "not connected" messages. Then, you successfully connect, so you print the "connected" message.

Then you send, and print, a bunch of useless junk.

You do NOT print whatever the server had to say, so you really don't know what it going on.

Get a flashlight. Stabbing in the dark is useless.

PaulS:
Why are you using a 32 bit array to hold 16 bit values?

No. It's the address of the server where the PHP script is. That does not have to be the same server that the database software is running. Though it usually is.

This is not necessary, unless the domain you are trying to talk to is being hosted on the same machine as many other domains.

No. You make a request to the server. The server generates a response. You MUST read the entire response. When you do, the connection will close automatically, so you don't need to.

Get rid of everything you are sending to the server after the HTTP/1.1 bit.
What parts do you think are contradictory? Initially, you are not connected to the server, so you print the "not connected" messages. Then, you successfully connect, so you print the "connected" message.

Then you send, and print, a bunch of useless junk.

You do NOT print whatever the server had to say, so you really don't know what it going on.

Get a flashlight. Stabbing in the dark is useless.

Alright, as i said, i don't know much about programming, let alone Arduino, hence why i'm asking for help.

I removed everything you told me to remove as it is unecessary, fixed the 32 bit array and got the ip right.

The prints were confusing me, thanks for explaining why it was printing the 'connected' and 'not connected', now that it is posting data to the db, my next step is to add the weatherstation and hopefully it will work.

I appreciate the help, it got the code a little bit clearer for me.