pr1m3x
pr1m3x

Reputation: 2087

How to pass variable in mysql_query

I try to execute mysql query passing variable. Here is my code

char str[100] = "My String";

mysql_query(conn, printf("INSERT INTO table VALUES %s"), str);

I get that warning during compile process

warning: passing argument 2 of ‘mysql_query’ makes pointer from integer without a cast

What I miss ?

Upvotes: 1

Views: 7833

Answers (3)

ckruse
ckruse

Reputation: 9740

You cannot do that. printf() returns the number of characters printed. You have to create the string before calling mysql_query():

char statement[512], *my_str = "MyString";
snprintf(statement, 512, "INSERT INTO table VALUES ('%s')", str);
mysql_query(conn, statement);

Also, be careful when creating those query strings. Don't use functions like sprintf() if you cannot be sure how long the resulting string is. Don't write over the boundaries of the memory segment.

Upvotes: 3

glglgl
glglgl

Reputation: 91017

Extending @ckruse's answer, you should take care to use mysql_real_escape_string() if your string comes from arbitrary sources.

int insert_data(MYSQL * mysql, char * str, int len)
{
    if (len < 0) {
        len = strlen(str);
    }

    char esc[2*len+1];
    unsigned long esclen = mysql_real_escape_string(mysql, esc, str, len);

    char statement[512];
    snprintf(statement, sizeof statement, "INSERT INTO table VALUES ('%s')", esc);
    return mysql_query(mysql, statement);
}

(An alternative could be mysql_hex_string() if dealt with correctly.)

Upvotes: 4

yossi
yossi

Reputation: 13315

you should put "'' in front and after the string like this

mysql_query(conn, printf("INSERT INTO table VALUES ('%s')"), str);

Upvotes: -1

Related Questions