#include <stdlib.h> #include <stdio.h> #include <mysql.h> #include <string.h> #include "cgi.h" #include "../tplcp/strct.h" #define PER_PAGE 15 char* display_error(tpl_data tpl, int *len); char* display_result(tpl_data tpl, int *len); void query(tpl_data tpl) { char* query; char* word = get_param("q"); MYSQL* sql = bdd_connect(); MYSQL_RES* result; MYSQL_ROW row; size_t limit = 0; size_t max = 0; //escape_free(sql, &word); query = get_param("p"); if (query) limit = atoi(query) * 15; query = malloc(400); sprintf(query, "SELECT COUNT(DISTINCT page) FROM keywords WHERE name LIKE '%s'", word); if (!mysql_query(sql, query)) { result = mysql_use_result(sql); row = mysql_fetch_row(result); max = atoi(row[0]); mysql_free_result(result); } sprintf(query, "SELECT DISTINCT page, url FROM keywords LEFT JOIN page ON page = pid WHERE name LIKE '%s' LIMIT %d, %d", word, limit, PER_PAGE); if (!mysql_query(sql, query)) { result = mysql_use_result(sql); query = realloc(query, 10000); word = malloc(500); row = mysql_fetch_row(result); query[0] = 0; while (row) { sprintf(word, "<a href=\"%s\">%s</a></br>\n", row[1], row[1]); query = strcat(query, word); row = mysql_fetch_row(result); } tpl_updt(tpl, "result", query); mysql_free_result(result); } if (limit) { sprintf(word, "<a href=\"?q=%s&p=%u\">Page precedente</a>", get_param("q"), limit - 1); tpl_updt(tpl, "pred", word); } if (limit < max / PER_PAGE) { sprintf(word, "<a href=\"?q=%s&p=%u\">Page suivante</a>", get_param("q"), limit + 1); tpl_updt(tpl, "suiv", word); } } void error() { char* page; int len = 0; tpl_data tpl = new_tpl(); page = display_error(tpl, &len); //puts("HTTP/1.0 400 Bad Request"); puts("Content-Type: text/html; charset=UTF-8"); printf("Content-Length: %d\n\n", len); puts(page); exit(0); } int main() { int len = 0; char* page; tpl_data tpl = new_tpl(); if (!get_param("q")) error(); query(tpl); page = display_result(tpl, &len); puts("Content-Type: text/html; charset=UTF-8"); printf("Content-Length: %d\n\n", len); puts(page); return 0; }