0

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 by gmunk: n/a

4
Contributors
8
Replies
10
Views
6 Years
Discussion Span
Last Post by aryan79
0

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 by Ancient Dragon: n/a

0

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 by tesuji: n/a

0

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

0

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 by tesuji: n/a

0

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

0

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.