Hi all,

lets say for example I have the following code

char *fname = "John";
char *lname = "Doe";
char *query = "SELECT fname, lname FROM table_name;"

The last statement won't work, so my question is how to pass the fname and lname variables to the query?

Recommended Answers

All 8 Replies

it has to be expanded.

char query[255];
sprintf(query,"SELECT %s, %s FROM table_name;",fname,lname);

But even the above is wrong because %s and %s need to represent column names, not data values. It's very unlikely the table has two columns named "John" and "Doe".

A more likely query might be "SELECT * FROM table_name WHERE lname = 'Doe' and fname = 'John'"

lets say for example I have the following code

char *fname = "John";
char *lname = "Doe";
char *query = "SELECT fname, lname FROM table_name;"

The last statement won't work, so my question is how to pass the fname and lname variables to the query?

** deleted ** (got it wrong)

I also prefer Ancient Dragon's suggestion much more than columm names John Doe.

"SELECT * FROM table_name WHERE lname = 'Doe' and fname = 'John'"

As for pure C you can create such sql string by concating char-arrays, for example:

sqls = (char *) malloc (200);  // some mem first
sqls[0] = '\0';                // don't forget this
strcat(sqls, "SELECT * FROM yourTable WHERE fname =   ");
strcat(sqls, fname);
strcat(sqls, "   AND lname =  ");
strcat(sqls, lname);
strcat(sqls, "  ; ");

Do you already know how to send this select string to database and receiving some data?

-- tesu

>>As for pure C you can concat char-arrays, for example:
That works too, its just a lot more typing and error prone than using sprintf(). Error prone meaning the more verbose the code the greater the chance of making mistakes. sprintf("SELECT * FROM table_name WHERE lname = '%s' and fname = '%s'", lname, fname);

Yes, your version is less error prone than strcat() and more gallant:

char sqls[200];
sprintf(sqls, "SELECT * FROM table_name WHERE lname = '%s' and fname = '%s';", lname, fname);

(You live and learn, thx :))

-- tesu

Thank you guys. I noticed my mistake, yeah its not very logical to have collumns John Doe. Thanks!

Hi,

I got how to put the query in sqls. But how to use this in mysql_query() in c. Can anyone help me for this.

Thanks

thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.