3

How do I write a C program which gets the client input for MySQL server? I'm using Fedora as my OS.

Here is my code:

#include<my_global.h>
#include<mysql.h>

main()
{
    char name[25];
    MYSQL *conn;
    conn=mysql_init(NULL);
    mysql_real_connect(conn,"localhost","root","","testdb",0,NULL,0);
    printf("Enter your name:");
    scanf("%s",name);
    mysql_query(conn,"CREATE TABLE Users(name VARCHAR(25))");

    mysql_query(conn,"INSERT INTO Users VALUES(name)");
    //mysql_query(conn,"INSERT INTO Users VALUES('Farhan')");
    //mysql_query(conn,"INSERT INTO Users VALUES('Dileep')");
    //mysql_query(conn,"INSERT INTO Users VALUES('RAJIV')");

    mysql_close(conn);
}

I want the client input to be stored in MySQL database and not the constant values.

1 Answer 1

1

Try sprintf'ing the name into your query, something like this:

int len = query_len + name_len + 1;
char * insert_query = (char *) malloc(len);
snprintf(insert_query, len, "INSERT INTO Users VALUES('%s')", name);

However, you'll need to take some care when checking the buffer lengths and especially escaping the name string.

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

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.