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?

Edited 6 Years Ago by gmunk: n/a

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'"

Edited 6 Years Ago by Ancient Dragon: n/a

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

Edited 6 Years Ago by tesuji: n/a

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

Edited 6 Years Ago by tesuji: n/a

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

This article has been dead for over six months. Start a new discussion instead.