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

int main(int argc, char **argv)
{

  MYSQL *conn;
  MYSQL_RES *result;
  MYSQL_ROW row;
  int num_fields;
  int i;
  char user_query[100];
  char word[10];

  printf("Enter word: ");
  scanf("%s", word);

  sprintf(user_query, "select * from english where word = %s", word);
  printf("%s\n", user_query);

  conn = mysql_init(NULL);
  mysql_real_connect(conn, "localhost", "root", "123", "test", 0, NULL, 0);

  mysql_query(conn, user_query);
  result = mysql_store_result(conn);

  num_fields = mysql_num_fields(result);

  while ((row = mysql_fetch_row(result)))
  {
      for(i = 0; i < num_fields; i++)
      {
          printf("%s ", row[i] ? row[i] : "NULL");
      }
      printf("\n");
  }

  mysql_free_result(result);
  mysql_close(conn);

  return 0;

}

Hey there daniweb community. Could anyone tell me why this code seg faults each time i run it. it compiles without errors, runs okay right up until where it prints out the mysql statement to confirmation, but seg faults after that, debug says it receives SIGSEGV signal at the num_fields = mysql_num_fields(result) line.

Thanks for any assistance with this. (Compiled on Ubuntu 12.04, Codeblocks GCC 4.6.3).

try this ? just check everywhere for NULL where possible :)

row = mysql_fetch_row(result)

while (row != NULL)
{
   for(i = 0; i < num_fields; i++)
   {
      //printf("%s ", row != NULL ? row[i] : "NULL");
      printf("%s", row[i]);
   }
   printf("\n");

   row = mysql_fetch_row(result)
}

@Sokurenko, thanks for replying, but still no dice. still seg faults at the same place.

Edit: Also tried changing the num_fields variable to type unsigned int (same return type as mysql_num_fields()) and still seg faults.

check conn for NULL, maybe failed to connect ? or result is NULL cause nothing found

Alright, been bashing away at this piece of troublesome code. finally got it working. it turns out i had an error in my syntax for the select statement.

Where:

sprintf(user_query, "select * from english where word = %s", word);

Should be:

sprintf(user_query, "select * from english where word = '%s'", word); //single quotes around %s

@Sokurenko, apologies for taking up your time with my own oversight.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.