1

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 ?

0

3 Answers 3

4

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.)

Sign up to request clarification or add additional context in comments.

2 Comments

Why do you choose int for len? int is not for array sizes, use size_t for that, or in case it can be negative use ptrdiff_t.
@12431234123412341234123 Most likely, I chose it to be "safe on the right side". mysql_real_escape_string() expects an unsigned long as its input length and also returns an unsigned long as its output size. This answer is from over 8 years ago, but quite likely I chose this type because it is hard to predict if the size_t will fit into the unsigned long, or vice versa. But most likely, it is better to use size_t. I was tempted to change my answer, but I don't know if I'll leave it as it is or I will change it.
3

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.

1 Comment

-1 This is a bad advice, when str contains something like f'); DROP TABLE table; -- and CLIENT_MULTI_STATEMENTS is set, then you lose all the data in table.
-1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.