0

I can't get the following code to work. It's working with normal select or insert, but when I try to insert a variable to it it didn't work. Can some let me know please what's wrong here?

Please note that the output is below.

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

  MYSQL *conn;
  char str[100] = "test";
  conn = mysql_init(NULL);

  char stmt_buf[100];
  sprintf (stmt_buf, "insert into test values ('%s')", str);

  printf("\n%s\n",stmt_buf);

  mysql_query (conn, stmt_buf);
  mysql_close(conn);
  return 0;
}

~$./version

insert into test values ('test')
Segmentation fault
8
  • You should run your program through GDB to find out where it's crashing. gdb ./version -> run Commented Feb 25, 2012 at 18:19
  • Did you try to compile your code with all warnings and debugging information (e.g. gcc -Wall -g), to improve your code till no warnings are given by the compiler, and to use a debugger (e.g. gdb)?? Commented Feb 25, 2012 at 18:21
  • I did but the output wasn't helpful as below. Program received signal SIGSEGV, Segmentation fault. 0x00199634 in mysql_send_query () from /usr/lib/libmysqlclient.so.16 Commented Feb 25, 2012 at 18:21
  • I always use -Wall -g and there was no error Commented Feb 25, 2012 at 18:24
  • 1
    -1: If you'd done any debugging whatsoever, you'd see that conn is 0x0. Commented Feb 25, 2012 at 18:48

2 Answers 2

2

You don't do any error checking. My guess is conn == NULL.

For the record, don't use sprintf ever. Use snprintf instead, that is, if you're okay with SQL injections.

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

Comments

1

I didn't see you are connected to database by mysql_real_connect also there is no mysql_select_db and mysql_exec_sql call.

Here is an example for you.

int main(int argc, char **argv)
{
    MYSQL mysql;
    char stmt_buf[100];
    if (mysql_init(&mysql) == NULL) {
        printf("Can not initialize");
        exit(1);
    }
    if (!mysql_real_connect
        (&mysql, "localhost", "USERNAME", "PASSWORD", NULL, 0, NULL, 0)) {
        mysql_error(&mysql);
        exit(1);
    }

    if (mysql_select_db(&mysql, "DATABASENAME")) {
        mysql_error(&mysql);
        exit(1);
    }

    sprintf(stmt_buf, "insert into test values ('%s')", "test");

    if (mysql_exec_sql(&mysql, stmt_buf))
        mysql_error(&mysql));

    mysql_close(&mysql);
}

1 Comment

Please note: this is a SQL injection waiting to happen if someone replaces "test" with untrusted user input. xkcd.com/327

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.