How to do it…

  1. Initialize a MYSQL object:
mysql_init(NULL);
  1. Establish a connection to the MySQL server running at the specified host. Also, establish a connection to the ecommerce database:
mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)
  1. Enter the email address of the user whose details you want to search for:
printf("Enter email address to search: ");
scanf("%s", emailaddress);
  1. Create an SQL SELECT statement that searches the row in the users table that matches the email address that was entered by the user:
strcpy(sqlquery,"SELECT * FROM users where email_address like \'");
strcat(sqlquery,emailaddress);
strcat(sqlquery,"\'");
  1. Execute the SQL SELECT statement. Terminate the program if the SQL query does not execute or some error occurs:
if (mysql_query(conn, sqlquery) != 0)                                 
{ fprintf(stderr, "No row found in the users table with this email address\n");
exit(1); }
  1. If the SQL query executes successfully then the row(s) that matches the specified email address are retrieved and assigned to a resultset:
resultset = mysql_use_result(conn);
  1. Use a while loop to extract one row at a time from the resultset and assign it to the array row:
while ((row = mysql_fetch_row(resultset)) != NULL)
  1. The information of the entire row is shown by displaying the subscripts row[0], row[1], and row[2], respectively:
printf("Email Address: %s \n", row[0]);
printf("Password: %s \n", row[1]);
printf("Address of delivery: %s \n", row[2]);
  1. Memory that's allocated to the resultset is freed up:
mysql_free_result(resultset);
  1. The opened connection handler is closed:
mysql_close(conn);

The searchuser.c program for searching in a specific row in a MySQL database table is shown in the following code:

#include <mysql/mysql.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main() {
MYSQL *conn;
MYSQL_RES *resultset;
MYSQL_ROW row;
char *server = "127.0.0.1";
char *user = "root";
char *password = "Bintu2018$";
char *database = "ecommerce";
char emailaddress[30], sqlquery[255];
conn = mysql_init(NULL);
if (!mysql_real_connect(conn, server, user, password, database, 0,
NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
printf("Enter email address to search: ");
scanf("%s", emailaddress);
strcpy(sqlquery,"SELECT * FROM users where email_address like \'");
strcat(sqlquery,emailaddress);
strcat(sqlquery,"\'");
if (mysql_query(conn, sqlquery) != 0)
{
fprintf(stderr, "No row found in the users table with this
email address\n");
exit(1);
}
printf("The details of the user with this email address are as
follows:\n");
resultset = mysql_use_result(conn);
while ((row = mysql_fetch_row(resultset)) != NULL)
{
printf("Email Address: %s \n", row[0]);
printf("Password: %s \n", row[1]);
printf("Address of delivery: %s \n", row[2]);
}
mysql_free_result(resultset);
mysql_close(conn);
}

Now, let's go behind the scenes to understand the code better.