#include <mysql/mysql.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int strcmp_wrapper(void *a, void *b) {
return strcmp(*((char**)a), *((char**)b));
}
int main(int argc, char *argv[]) {
MYSQL dbh;
MYSQL_RES *result;
MYSQL_ROW row;
MYSQL_FIELD *fields;
char *sql, *first_name, ***field_names;
size_t len;
unsigned int i, j, num_fields, *col_order;
/* connect to the database */
mysql_init(&dbh);
mysql_real_connect(&dbh, NULL, "foo", "bar", "common", 0, NULL, 0);
/* build ourselves a properly escaped sql query */
len = strlen(argv[1]);
first_name = (char*) malloc(sizeof(char) * (len * 2 + 1));
mysql_real_escape_string(&dbh, first_name, argv[1], (unsigned long) len);
asprintf(&sql, " \
SELECT * \
FROM person p, email e, company c, operating_system o \
WHERE p.first_name = '%s' \
AND e.person_id = p.id AND c.person_id = p.id and o.person_id = p.id \
ORDER BY p.last_name \
LIMIT 10 \
", first_name);
free(first_name);
/* perform the query */
mysql_query(&dbh, sql);
free(sql);
result = mysql_store_result(&dbh);
num_fields = mysql_num_fields(result);
/* get list of column headers */
fields = mysql_fetch_fields(result);
field_names = (char***) malloc(sizeof(char**) * num_fields);
for (i = 0; i < num_fields; i++) {
field_names[i] = &fields[i].name;
}
/* sort list of column headers */
qsort(field_names, num_fields, sizeof(char*), strcmp_wrapper);
/* generate column order array and output sorted headers */
col_order = (unsigned int*) malloc(sizeof(unsigned int) * num_fields);
for (i = 0; i < num_fields; i++) {
for (j = 0; j < num_fields; j++) {
if (fields[i].name == *field_names[j]) {
col_order[i] = j;
continue;
}
}
fputs(*field_names[i], stdout);
putchar((i == (num_fields-1)) ? '\n' : '\t');
}
free(field_names);
/* output data */
while ((row = mysql_fetch_row(result))) {
for (i = 0; i < num_fields; i++) {
fputs(row[col_order[i]], stdout);
putchar((i == (num_fields-1)) ? '\n' : '\t');
}
}
/* cleanup */
free(col_order);
free(fields);
mysql_free_result(result);
exit(0);
}