/* Collection of code snippets by Arne Vajhøj */
/* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SOCKET int
#include <mysql.h>

static char *parse(char *line, char *marker)
{
    char *p = strstr(line, marker);
    if(p == NULL)
    {
        return NULL;
    }
    else
    {
        char *res = malloc(strlen(line) + 1);
        p = p + strlen(marker);
        char *p2 = p;
        while(*p2 && *p2 != '&') p2++;
        memcpy(res, p, p2 - p);
        res[p2 - p] = 0;
        for(int i = 0; i < strlen(res); i++) if(res[i] == '+') res[i] = ' ';
        return res;
    }
}

int main()
{
    char *q = getenv("QUERY_STRING");
    char *q_f1 = parse(q, "f1=");
    int stat;
    MYSQL *con = mysql_init(NULL);
    con = mysql_real_connect(con, "localhost", "root", "", "test", 3306, NULL, 0);
    MYSQL_STMT *stmt = mysql_stmt_init(con);
    char *sqlstr = "DELETE FROM t1 WHERE f1 = ?";
    stat = mysql_stmt_prepare(stmt, sqlstr, strlen(sqlstr));
    MYSQL_BIND in[1];
    int f1 = atoi(q_f1);
    memset(in, 0, sizeof(in));
    in[0].buffer_type = MYSQL_TYPE_LONG;
    in[0].buffer = &f1;
    in[0].buffer_length = sizeof(f1);
    in[0].is_null= 0;
    stat = mysql_stmt_bind_param(stmt, in);
    stat = mysql_stmt_execute(stmt);
    mysql_stmt_free_result(stmt);
    mysql_close(con);
    char *EXTRA = "\r\n";
    printf("Location: http://arne1.vajhoej.dk/cgi-bin/show%s\n", EXTRA);
    printf("%s\n", EXTRA);
    return 0;
}
