Jason
Jason

Reputation: 15

When i try to insert my variable into my database it is inserted as a zero and not the expected value

This is an example from my code. I am trying to insert currentTemp into my database but the entry in my databse gives 0 back as a result from the insert and not the value of the variable currentTemp. Can anyone tell me how to do this properly.

#include <unistd.h>  
#include <stdio.h>   
#include <mysql/mysql.h>
#include <my_global.h>

int main (int argc, char* argv[]){

int val = 280;
int currentTemp = (val / 4) - 50;

//while true loop
while(1) {

    //login 
    char *server = "server";
    char *user = "user";
    char *password = "pass";
    char *database = "database";

    // Verbinding maken met de database.
    conn = mysql_init(NULL);
    if (!mysql_real_connect(conn, server,user, password, database, 0, NULL,0)){
        fprintf(stderr, "%s\n", mysql_error(conn));
    }

    //Query for putting currentTemp into my database
    if(mysql_query(conn, "INSERT INTO temperature VALUES(currentTemp)")!=0){
        mysql_error(conn);
    }    
}

Upvotes: 0

Views: 34

Answers (1)

P.P
P.P

Reputation: 121427

You haven't really inserted the value here:

if(mysql_query(conn, "INSERT INTO temperatuur VALUES(currentTemp)")!=0)

You need to use snprintf() and print currentTemp and use it:

char buf[1024];

snprintf(buf, sizeof buf, "INSERT INTO temperatuur VALUES(%d)", currentTemp);
if(mysql_query(conn, buf) != 0 )  {
   ....
}

Upvotes: 2

Related Questions