//***************************************************************************************
// C Read data from Mysql database 
//***************************************************************************************
#include <stdio.h>
#include <stdlib.h>
#include <mysql/mysql.h>

int main() {
    MYSQL       *conn;
    MYSQL_RES   *res;
    MYSQL_ROW   row;

    const char *server   = "localhost";         // Host server address
    const char *user     = "demo2";             // Database username
    const char *password = "demo2";             // Database password
    const char *database = "demo2";             // Database name

    // Initialize the connection
    conn = mysql_init(NULL);
    if (!conn) {
        fprintf(stderr, "mysql_init() failed \n");
        return EXIT_FAILURE;
    }

    // Connect to the database
    if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) 
    {
        fprintf(stderr, "mysql_real_connect() failed. Error: %s\n", mysql_error(conn));
        mysql_close(conn);
        return EXIT_FAILURE;
    }

    char sql[] = "SELECT * FROM addrbook " \
                 "ORDER BY 1 "; 

    // Execute SQL query
    int ok = mysql_query(conn, sql); 
    if (ok != 0) {
        fprintf(stderr, "SELECT query failed. Error: %s\n", mysql_error(conn));
        mysql_close(conn);
        return EXIT_FAILURE;
    }

    // Store and process result
    res = mysql_store_result(conn);
    if (!res) {
        fprintf(stderr, "mysql_store_result() failed. Error: %s\n", mysql_error(conn));
        mysql_close(conn);
        return EXIT_FAILURE;
    }

    // Print column names
    int num_fields = mysql_num_fields(res);

    MYSQL_FIELD *fields = mysql_fetch_fields(res);
    for (int i = 0; i < num_fields; i++) {
        printf("%s\t", fields[i].name);
    }
    printf("\n");

    // Print each row
    while (row = mysql_fetch_row(res)) 
    {
        for (int i = 0; i < num_fields; i++) 
           printf("%s\t", row[i] ? row[i] : "NULL");
        printf("\n");
    }

    // Clean up
    mysql_free_result(res);
    mysql_close(conn);

    printf("Data displayed successfully.\n");
    return EXIT_SUCCESS;
}